gpt4 book ai didi

c# - Entity Framework 循环引用

转载 作者:可可西里 更新时间:2023-11-01 08:21:59 25 4
gpt4 key购买 nike

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

所以我非常困惑并优先使用 Entity Framework 代码

我有一个 Forest 类。

我有一个树类。

每个森林可以有很多棵树

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

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;}
}

每片森林都有树木,但并非每棵树都在森林中。我在做的时候遇到了多重性错误

@(Html.Raw(Json.Encode(Model)))

模型是森林

如果我将 ForestId 设为 Guid 而不是 Guid?,我会收到循环引用错误。

我也试过 protected 覆盖无效

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

提前致谢

最佳答案

最好的方法是您应该使用 DTO 仅将您想要的数据传输到客户端。 DTO 应该只有简单的属性,这样就不会产生循环引用错误。目前森林有List<Trees> Trees每个 Tree在 Trees 中有 ForestForest又有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;}
}

编辑:

连同 ScriptIgnore你还应该删除 virtual来自 ForestTrees那会起作用的。我已经测试过了。但是,我不建议这样做,因为 virtual 关键字是延迟加载的原因。因此,正如我所说,您需要基于这些模型创建 DTO,并且只将 DTO 发送给客户端。

关于c# - Entity Framework 循环引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12811975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com