实体框架循环引用 [英] Entity Framework Circular Reference
问题描述
再次尝试这个问题,因为我第一次尝试了几乎一致的:P
Trying this question again because my first attempt was barely coherent :p
所以我超困惑和使用实体框架代码首先
So I am super confused and using Entity Framework Code First
我有一个森林类。
我有一个Tree类。
每个森林可以有许多树木
Each Forest can have many Trees
当我试图序列化我得到循环引用
When I was trying to serialize I was getting circular reference
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;}
}
每个林中有树,但不是每一种树是一片森林。我做
Every forest has trees but not every tree is in a forest. I struggle with either errors of Multiplicity when doing
@(Html.Raw(Json.Encode(Model)))
当模型是森林
如果我让 ForestId
A 的Guid
,而不是的Guid?
我得到循环引用错误。
and if I make ForestId
a Guid
instead of a Guid?
I get Circular Reference errors.
我也试过
保护覆盖无效
I also tried protected override void
OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
modelBuilder.Entity<Forest>()
.HasMany(x => x.Tree)
.WithOptional()
.HasForeignKey(y => y.ForestId);
}
在此先感谢
Thanks in advance
推荐答案
最好的办法是,你应该使用DTO的传输只想要客户端的数据。该DTO的应该只是简单的属性,所以它不会产生循环引用错误。目前,森林具有列表<树木与GT;树
,每个树
树有森林
和林内
又有列表<树>
Best approach would be you should use DTOs to transfer only the data that you want to the client. The DTOs should have just simple properties so it won't create a circular reference error. At the moment the Forest has List<Trees> Trees
and each Tree
within Trees has Forest
and that Forest
again has List<Trees>
或
您可以用装饰 ScriptIgnore
您的属性,对于您不希望
Json.Encode性能序列化,然后,将不会被发送回客户端。
You can decorate your attributes with ScriptIgnore
for properties that you don't want the
Json.Encode to serialize and then that wouldn't be sent back to the client.
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
你也应该删除虚拟
从森林
和树
,这会工作。我测试过它。不过,我不会建议,由于虚拟的关键字是什么呢延迟加载。因此,正如我所说,你需要根据这些模型来创建的DTO,仅在发送DTO客户。
Along with ScriptIgnore
you should also remove virtual
from Forest
and Trees
and that would work. I've tested it. However, I wouldn't advise that because virtual keyword is what does the Lazy loading. Hence as I said you need to create DTOs based on these Models and only send in DTO to client.
这篇关于实体框架循环引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!