再次尝试这个问题,因为我的第一次尝试几乎没有连贯性:p
所以我非常困惑并使用 Entity Framework Code First
我有一个森林课。
我有一个树类。
每个森林可以有很多树
当我尝试序列化时,我得到了循环引用
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
a Guid
代替Guid?
我收到循环引用错误。
我也尝试过
受保护的覆盖无效
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
树内有Forest
然后Forest
再次有List<Trees>
Or
你可以用以下方式装饰你的属性ScriptIgnore
对于您不想要的属性
Json.Encode 进行序列化,然后不会发送回客户端。
http://msdn.microsoft.com/en-us/library/system.web.script.serialization.scriptignoreattribute.aspx
Eg:
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;}
}
Edit:
随着ScriptIgnore
你还应该删除virtual
from Forest
and Trees
那会起作用的。我已经测试过了。但是,我不建议这样做,因为 virtual 关键字是延迟加载的作用。因此,正如我所说,您需要基于这些模型创建 DTO,并且仅将 DTO 发送给客户端。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)