实体框架循环参考

Jor*_*dan 12 c# entity-framework code-first

再次尝试这个问题,因为我的第一次尝试几乎没有连贯性:p

所以我非常困惑并使用Entity Framework Code First

我有一个Forest类.

我有一个Tree类.

每个森林都有很多树

当我试图序列化时,我得到了循环引用

public class Forest
{

    public Guid ID { get; set; }  
    public virtual List<Tree> Trees { get; set; }
}
public class Tree
{
    public Guid ID { get; set; }
    public Guid? ForestId {get;set;}

    [ForeignKey("ForestId")]
    public virtual Forest Forest {get;set;}
 }
Run Code Online (Sandbox Code Playgroud)

每个森林都有树木,但不是每棵树都在森林里.这样做时,我会遇到Multiplicity的错误

@(Html.Raw(Json.Encode(Model)))
Run Code Online (Sandbox Code Playgroud)

模型是森林的地方

如果我做ForestId了一个Guid而不是Guid?我得到循环引用错误.

我也尝试过protected override void

OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder) 
{ 
  modelBuilder.Entity<Forest>() 
  .HasMany(x => x.Tree) 
  .WithOptional() 
   .HasForeignKey(y => y.ForestId); 
}
Run Code Online (Sandbox Code Playgroud)

提前致谢

TCM*_*TCM 16

最好的方法是你应该使用DTO只将你想要的数据传输到客户端.DTO应该只具有简单的属性,因此不会产生循环引用错误.目前森林已经List<Trees> Trees 和每个Tree树内都有Forest,而且Forest又有List<Trees>

要么

您可以使用ScriptIgnore不希望Json.Encode序列化的属性来装饰属性,然后将不会将其发送回客户端.

http://msdn.microsoft.com/en-us/library/system.web.script.serialization.scriptignoreattribute.aspx

例如:

public class Forest
{    
    public Guid ID { get; set; }  
    public virtual List<Tree> Trees { get; set; }
}
public class Tree
{
    public Guid ID { get; set; }
    public Guid? ForestId {get;set;}

    [ForeignKey("ForestId")]
    [ScriptIgnore]
    public virtual Forest Forest {get;set;}
 }
Run Code Online (Sandbox Code Playgroud)

编辑:

随着ScriptIgnore你也应该删除virtual从Forest与Trees那会工作.我测试过了.但是,我不建议,因为虚拟关键字是懒惰加载.因此,正如我所说,您需要根据这些模型创建DTO,并仅将DTO发送给客户.