相关疑难解决方法(0)

实体框架循环参考

再次尝试这个问题,因为我的第一次尝试几乎没有连贯性: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)

提前致谢

c# entity-framework code-first

12
推荐指数
1
解决办法
1万
查看次数

标签 统计

c# ×1

code-first ×1

entity-framework ×1