Avoiding Circular referencing providing too much data

淺唱寂寞╮ 提交于 2019-12-12 03:39:17

问题


I followed all the procedures to avoid circular referencing in my Wines/Vineyard project. But I am getting data I do not want:

I do not want every listing of wine which has an affiliated vineyard to then have that vineyard list EVERY wine every time the vineyard is listed per wine. How can I stop this? I do not want to do anonymous types.

UPDATE:

My DbContext:

    public DataContext()
    {
        Configuration.LazyLoadingEnabled = false;
        Configuration.ProxyCreationEnabled = false;
    }

My Route Config:

        config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

My Controller:

var response = context.Wines.Include("Vineyard").ToList();


回答1:


How are you serializing your data?

Just don't serialize your wines collection property. Depending on your serialization mechanism you can either mark it with an attribute (ie. ScriptIgnore) or define concrete types (since you don't like anonymous types) and use AutoMapper to copy data.

Binding your EF entities directly to the response of the API is not the best design choice. Every time you modify your db schema your API will change. You could define separate classes that your API controllers will return and use AutoMapper to copy data. That way you decouple your DB schema from your API.

namespace API {
    class Wine {
        // properties that you want to return goes here
    }
}

Mapper.CreateMap<Wine, API.Wine>(); // Only once during app start
Mapper.Map<Wine, API.Wine>(wine); // AutoMapper will copy data using conventions


来源:https://stackoverflow.com/questions/13981372/avoiding-circular-referencing-providing-too-much-data

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