Question

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

enter image description here

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();

Était-ce utile?

La solution

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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top