1

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.

Community
  • 1
  • 1
Matthew Shea
  • 567
  • 5
  • 14

2 Answers2

2

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 1
    This is what I was thinking initially, but I was really hoping to not have to manually specify all of the properties in the new type. I'll keep digging a bit more. – Matthew Shea Feb 21 '13 at 21:59
1

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;
qujck
  • 14,388
  • 4
  • 45
  • 74