Why my super simple ASP.NET Web API (mvc4)+Entity Framework 5 doesn't work?

前端 未结 2 995
天涯浪人
天涯浪人 2020-12-11 12:01

I spent days to know the problems of my work, but no luck.

  1. I created new MVC4 Web API project.
  2. Add EF5 with my database (Project>Add>ADO.NET Entity Da
相关标签:
2条回答
  • 2020-12-11 12:24

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

    Add below code in Global.asax solves the problem.

    var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
    json.SerializerSettings.PreserveReferencesHandling = 
    Newtonsoft.Json.PreserveReferencesHandling.All;
    
    0 讨论(0)
  • 2020-12-11 12:43

    The reason the serialization fails are yours Navigation Properties - while the serializer is trying to walk the object graph they result in circular dependencies.

    For your simple sample to work you have few ways around it.

    1. Remove Navigation Property Sheet from SheetDetail
    2. Wrap your objects in ViewModel classes with Navigation Property Sheet omitted
    3. Create a metadata class with JsonIgnoreAttribute and then attach it to your entity with partial class and MetadataTypeAttribute

    Here you can find sample for third solution (sample makes some assumptions as I don't know your exact data types):

    public class SheetDetailSerializationMetadata
    {
        [JsonIgnore]
        public Sheet Sheet { get; set; }
    }
    
    [MetadataType(typeof(SheetDetailSerializationMetadata))]
    public partial class SheetDetail
    { 
    }
    
    0 讨论(0)
提交回复
热议问题