简体   繁体   中英

How do I prevent an MVC4 ApiController from serializing Entity Framework Navigation Properties?

I have an ApiController that works with Entity Framework objects. The particular object I am trying to return on the GET request has almost a dozen Navigation Properties.

When I return the list of EF objects, it serializes all navigation properties , which results in a ridiculous amount of time being taken serializing the object,

    public IEnumerable<EFObject> Get()
    {
        IEnumerable<EFObject> EFObjects=
            db.EFObject;

        return EFObject;

    }

How can I prevent MVC from serializing these navigation properties?

I have tried this and it did not work.

How can I prevent MVC from serializing these navigation properties?

By using a view model of course and then having your controller action return this view moedl instead of your domain model. The view model will be specifically defined to contain only the properties you want. You might also find AutoMapper useful for mapping between your domain models and your view models.

The best practice is to always expose view models from your methods and never make your domain entities visible outside those methods. An additional benefit you will get from this approach is that your API will be resilient to changes in your domain models and this could be done without breaking existing clients.

You can try the [XmlIgnore] attribute.

a lot depends on the rest of the technology stack etc. I'm using WebApi and have this code in the WebApiConfig.cs file and navigation properties are ignored. I'm always returning xml, not json.

var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
xml.UseXmlSerializer = true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM