[英]Implementing IEntityWithRelationships causes related objects to stop loading
我有兩個建立了多對多關系的實體:
類別:
public class Category : IEntityWithRelationships
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public virtual ICollection<User> Users { get; set; }
//Json.NET needs this in order to serialize the object
private RelationshipManager rm;
RelationshipManager IEntityWithRelationships.RelationshipManager
{
get
{
if (rm == null)
rm = RelationshipManager.Create(this);
return rm;
}
}
}
和用戶:
public class User
{
public int Id { get; set; }
public ICollection<Category> Categories { get; set; }
}
相關對象加載良好,但是隨后我需要將類別對象序列化為Json,並且Json.Net不斷拋出:
RelationshipManager對象無法序列化。 當RelationshipManager屬於未實現IEntityWithRelationships的實體對象時,無法序列化此類型的對象。
因此,我實現了IEntityWithRelationships
接口,但是現在我的相關對象沒有加載。
我嘗試了一個自定義的ContractResolver
,但是上面仍然有異常。 如何獲取相關對象?
您不能在EF
類中具有這種接口,因為這樣EF
不會創建代理的=> Lazy loading
已關閉。 http://msdn.microsoft.com/zh-CN/library/dd468057.aspx 。 其實人建議關掉LazyLoading
時,你必須系列化你entties(當然,實現該接口是不這樣做正確的方式)。 您應該准備更多有關如何在序列化中使用EntityFramework
。
您不應在代碼優先實體中實現該接口。 實現該接口違反了POCO。 它是“大量” EF實體使用的接口,通過使用它,您將失去EF處理POCO的方式。
我想您要這樣做的唯一原因是循環引用有問題。 您應該能夠解決此問題,而無需指定任何特定於API的接口。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.