Why is my super simple ASP.NET Web API (mvc4) + Entity Framework 5 not working?

I spent days to find out about the problems of my work, but no luck.

  • I created a new MVC4 Web API project.
  • Add EF5 with my database (Project> Add> ADO.NET Entity Data Model> Create from a database located in Azure SQL).
  • Add two tables to edmx as shown below. And two * .tt files will successfully generate entities and model classes.

enter image description here

I see that a breakpoint (result) usually gives the result of the query. But json gives an abnormal stream without error message. (i.e. http://localhost:41813/api/sheet/157 returns "157" which cannot be loaded. In general, "157.json" is loaded)

enter image description here

I copied the properties in the results to my handmade POCO style class and it works.

What is my problem? I cannot use the generated model classes to send data via Json. I hardly recognize the problem, because after the breakpoint of the result there is no error message without debugging.

+1
source share
2 answers

The reason why serialization fails is your navigation property - while the serializer tries to go through the graph of objects, they lead to cyclic dependencies.

For your simple work example, you have several ways around it.

  • Remove Sheet navigation property from SheetDetail
  • Wrap objects in ViewModel classes using the Navigation Sheet omitted property
  • Create a metadata class using JsonIgnoreAttribute and then attach it to your entity with a partial class and MetadataTypeAttribute

Here you can find a sample for the third solution (the sample makes some assumptions, because I do not know your exact data types):

 public class SheetDetailSerializationMetadata { [JsonIgnore] public Sheet Sheet { get; set; } } [MetadataType(typeof(SheetDetailSerializationMetadata))] public partial class SheetDetail { } 
+6
source

As a comment by @danludwig, http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization gives all the answers about my problem.

Add the code below to Global.asax to solve this problem.

 var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter; json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.All; 
0
source

Source: https://habr.com/ru/post/1443822/


All Articles