Circular reference causing stack overflow with Automapper

后端 未结 5 962
不思量自难忘°
不思量自难忘° 2020-11-29 09:29

I\'m using Automapper to map my NHibernate proxy objects (DTO) to my CSLA business objects

I\'m using Fluent NHibernate to create the mappings - this is working fine

5条回答
  •  难免孤独
    2020-11-29 09:52

    Since this is the #1 google search result, I think there might be some people, like me, coming here who don't get a stackoverflow exception, but find trouble when sending the object (via ASP.NET) to the client, and thus it being JSON serialized.

    So I had the same structure in place, Invoices has multiple InvoiceLines, when I load an Invoice and use the Linq-to-SQL .Include(x => x.InvoiceLines) I get errors when I try to load the object from the Api because each InvoiceLine contains the same Invoice again.

    To solve this, do the following in ASP.NET Core Startup class:

    services.AddMvc().AddJsonOptions(o =>
    {
        o.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        o.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
        o.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
        // ^^ IMPORTANT PART ^^
    }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    

    So include o.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects; in your JsonConfiguration when adding MVC to your application.

    JSON.Net is taking the extra step to setup each reference with an additional meta-property called “$id”. When JSON.Net encounters the same instance in another place in the object graph, it simply drops a reference to the original instance, instead of duplicating the data, and thus not causing circular reference issues!

    Source: https://johnnycode.com/2012/04/10/serializing-circular-references-with-json-net-and-entity-framework/

    So now I don't have to further edit my AutoMapper configuration.

提交回复
热议问题