[英]How do I prevent an MVC4 ApiController from serializing Entity Framework Navigation Properties?
I have an ApiController that works with Entity Framework objects. 我有一个与Entity Framework对象一起使用的ApiController。 The particular object I am trying to return on the GET request has almost a dozen Navigation Properties.
我试图在GET请求上返回的特定对象有几十个导航属性。
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, 当我返回EF对象列表时,它会序列化所有导航属性 ,这会导致序列化对象的时间过长,
public IEnumerable<EFObject> Get()
{
IEnumerable<EFObject> EFObjects=
db.EFObject;
return EFObject;
}
How can I prevent MVC from serializing these navigation properties? 如何阻止MVC序列化这些导航属性?
How can I prevent MVC from serializing these navigation properties?
如何阻止MVC序列化这些导航属性?
By using a view model of course and then having your controller action return this view moedl instead of your domain model. 通过使用视图模型,然后让控制器操作返回此视图moedl而不是域模型。 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. 您可能还会发现
AutoMapper
对于您的域模型和视图模型之间的映射非常有用。
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.
您将从此方法中获得的另一个好处是,您的API可以适应您的域模型中的更改,并且可以在不破坏现有客户端的情况下完成此操作。
You can try the [XmlIgnore]
attribute. 您可以尝试
[XmlIgnore]
属性。
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. 很大程度上取决于技术堆栈的其余部分等。我正在使用WebApi并在WebApiConfig.cs文件中使用此代码并忽略导航属性。 I'm always returning xml, not json.
我总是返回xml,而不是json。
var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
xml.UseXmlSerializer = true;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.