Self referencing loop Detected for property in Asp.net MVC with Angular 2

℡╲_俬逩灬. 提交于 2019-12-24 19:44:19

问题


  1. I Have Create a DB in that I am Having Multiple tables having Relationship between them.
  2. When a try to get data from my WEb app i get this error

    "'Self referencing loop detected with type 'System.Data.Entity.DynamicProxies.PrescriptionMaster_2C4C63F6E22DFF8E29DCAC8D06EBAE038831B58747056064834E80E41B5C4E4A'. Path '[0].Patient.PrescriptionMasters"

  3. I coudn't get why i am getting this error, and when i remove the relationships between tables i get proper data From it.
  4. I have Tried other solutions like adding

    "config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; "

    in Webconfig.cs but nothing has worked for me.

Please help me, what should I do ?


回答1:


The only proper way to prevent this from happening is by not sending Entity Framework objects (which may contain such loops) into the JSON Serializer (which is not too good at knowing when to stop serializing).

Instead, create ViewModels that mimic the parts of the EF Objects that your Front End actually needs, then fill those ViewModels using the EF Objects.

A quick-and-dirty way is to just use anonymous objects, for example:

return new
{
    Product = new
    {
        Id = EF_Product.Id,
        Name = EF_Product.Name
    }
};

A good rule-of-thumb is to only assign simple properties (number, bool, string, datetime) from the EF Objects to the ViewModel items. As soon as you encounter an EF Object property that is yet another EF Object (or a collection of EF Objects), then you need to translate those as well to 'simple' objects that are not linked to EF.

On the other end of the spectrum there are libraries such as AutoMapper. If you decide that you need actual ViewModel classes, then AutoMapper will help mapping the EF Objects to those ViewModels in a very structured way.




回答2:


Just add this to the Application_Start in Global.asax:

HttpConfiguration config = GlobalConfiguration.Configuration;

config.Formatters.JsonFormatter
            .SerializerSettings
            .ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

It will ignore the reference pointing back to the object.



来源:https://stackoverflow.com/questions/47449870/self-referencing-loop-detected-for-property-in-asp-net-mvc-with-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!