0

I'm trying to make an API with joining multiple tables, and I'm not getting the return end, I do not know what I'm doing wrong.

My db

This code works perfectly within the Views Controller in csHtml but in the API I am not getting, see below the code trying to use in the API and that works on the Controller responsible for View cshtml.

    // GET: api/SequenciasAPI
    public IQueryable<Sequencia> GetSequencias()
    {
        var sequenciaViewModel = new SequenciaViewModel();
        sequenciaViewModel.Lado_A = new Lado();

        sequenciaViewModel.Lote = new Lote();
        sequenciaViewModel.Sequencia = new Sequencia();
        sequenciaViewModel.LadoList = new List<Lado>();
        sequenciaViewModel.LoteList = new List<Lote>();
        sequenciaViewModel.SequenciaList = new List<Sequencia>();
        sequenciaViewModel.TipoLadosList = new List<TipoLado>();

        DateTime dt = DateTime.Now.Date;

        var svm = db.Sequencias.Where(a => a.DataAbate == dt).OrderByDescending(b => b.NumeroSequencia).ToList();

        foreach (var item in svm)
        {
            sequenciaViewModel.SequenciaList.Add(item);

            var svmSequenciaLado = db.SequenciaLados.Where(p => p.SequenciaId == item.SequenciaId).ToList();

            for (int i = 0; i < item.SequenciaLado.Count(); i++)
            {
                var lado = new Lado()
                {
                    Nome = item.SequenciaLado.ElementAt(i).Lado.Nome,
                };
                sequenciaViewModel.LadoList.Add(lado);

                var tipoLado = new TipoLado()
                {
                    Nome = item.SequenciaLado.ElementAt(i).Lado._TipoLado.Nome
                };
                sequenciaViewModel.TipoLadosList.Add(tipoLado);
            }
        }

        return sequenciaViewModel;
    }

Class used to refer to tables SequenciaViewModel

public class SequenciaViewModel
{
    public Lote Lote { get; set; }

    public Sequencia Sequencia { get; set; }

    [Display(Name = "Genero")]
    public TipoGenero Tipo_Genero { get; set; }

    [Display(Name = "Lado A")]
    public Lado Lado_A { get; set; }

    [Display(Name = "Lado B")]
    public Lado Lado_B { get; set; }

    public SequenciaLado Sequencia_Lado { get; set; }

    public List<Lote> LoteList { get; set; }

    public List<Sequencia> SequenciaList { get; set; }

    public List<TipoGenero> TipoGeneroList { get; set; }

    public List<Lado> LadoList { get; set; }

    public List<TipoLado> TipoLadosList { get; set; }

    public List<SequenciaLado> SequenciaLadosList { get; set; }
}

Message error

{
    "Message": "An error has occurred.",
    "ExceptionMessage": "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.",
    "ExceptionType": "System.InvalidOperationException",
    "StackTrace": null,
    "InnerException": {
        "Message": "An error has occurred.",
        "ExceptionMessage": "Self referencing loop detected with type 'System.Data.Entity.DynamicProxies.Sequencia_73791DF529E39EC47D26865784B2E5ED3CFBB9AF9771CECF4D2BD5BC586DA283'. Path 'SequenciaList[0]._TipoGenero._Sequencias'.",
        "ExceptionType": "Newtonsoft.Json.JsonSerializationException",
        "StackTrace": "   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CheckForCircularReference(JsonWriter writer, Object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)\r\n   em Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)\r\n   em System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n   em System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n   em System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)\r\n   em System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- Fim do rastreamento de pilha do local anterior onde a exceção foi gerada ---\r\n   em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   em System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()"
    }
}
Cyberlacs
  • 191
  • 1
  • 7

1 Answers1

0

You are declaring the api method to return an IQueryable of type Sequencia but you are instead returning an instance of SequenciaViewModel. So the first question is Does this even compile?

When defining the api endpoint, there's no point of sending an IQueryable as this is the end of line before the data reaches the client. Therefore, define the method to just return the SequenciaViewModel type

public SequenciaViewModel GetSequencias()
{
    ....your logic

    return sequenciaViewModel;
}

Update: To solve your exception, you need to tell your json serializer to ignore self referencing, add the following in the Global.asax application start method

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
    .ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
Marcus Höglund
  • 16,172
  • 11
  • 47
  • 69
  • I did what you asked me right up and NOW is compiling, but this is returning me error in Postman - "ExceptionType": "Newtonsoft.Json.JsonSerializationException", – Cyberlacs Sep 18 '18 at 18:44
  • I'm going to have to do an sql inner join to get the values and thus see if I get the desired values – Cyberlacs Sep 18 '18 at 18:46
  • @Cyberlacs one other thing, Remove the Display attributes from the model. They are only for mvc views. If sending this model through an api they are not needed and might be the answer to why the json serializationis not working – Marcus Höglund Sep 18 '18 at 18:48
  • You're telling me that I should remove the [Display (Name = "Gender")] so that's why it's giving me error, I've removed it and it's still giving error? – Cyberlacs Sep 18 '18 at 18:57
  • @Cyberlacs ok, could you add the comlete exception msg with stack trace? – Marcus Höglund Sep 18 '18 at 19:23
  • I updated topic of my question as per your request Message error Postman – Cyberlacs Sep 18 '18 at 20:36
  • @Cyberlacs updated the answer – Marcus Höglund Sep 19 '18 at 06:40