实体框架ProxyCreation已禁用,但仍需要访问某些相关的记录数据

时间:2013-03-18 03:31:14

标签: entity-framework

根据StackOverflow的一些建议,我使用下面的代码在dbContext中关闭了ProxyCreation以解决循环引用问题

_dbcontext.Configuration.ProxyCreationEnabled = false;

关闭它后,Json序列化返回我的相关类型的null,这有望解决循环引用,但如果我仍然需要某种类型该怎么办。例如,我可以从我的EntityChild访问EntityParentType

EntityChild.EntityParentType(它们在数据库中与外键关系相关,EntityParenetTypeId)。

我试过.Include(“EntityParentType”)但我再次回到循环引用问题。完成这项工作的正确方法是什么?

    var result = from entry in EntityChild.Include("EntityParentType")
                 where entry.EntityParentTypeId == 1 
                 select entry;

编辑:使用ViewModel是解决此循环引用问题的最佳选择吗? http://garfbradazweb.wordpress.com/2011/09/22/mvc-3-entity-framework-and-serializing-jsoncircular-references/

1 个答案:

答案 0 :(得分:1)

您可以使用ScriptIgnore属性

忽略序列化中的父级或子级
public class Entity
{
    [ScriptIgnore]
    public Item ChildEntity { get; set; }
}