再次尝试这个问题,因为我的第一次尝试几乎没有一致:p
所以我超级混淆,并使用实体框架代码第一
我有森林课.
我有一个树类.
每个森林都可以有很多树木
当我试图序列化我正在获得循环引用
- 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?我收到循环引用错误.
我也试过
保护覆盖void
- OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
- {
- modelBuilder.Entity<Forest>()
- .HasMany(x => x.Tree)
- .WithOptional()
- .HasForeignKey(y => y.ForestId);
- }
提前致谢
解决方法
最好的方法是您应该使用DTO将您想要的数据传输到客户端. DTO应该具有简单的属性,因此不会创建循环引用错误.目前森林里有“树”和“树”树木和树木中的每棵树都有森林,那个森林里又有“树”和“树”.
要么
您可以使用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之外,您还应该从Forest和Trees中删除虚拟机,这样就可以运行.我已经测试了但是,我不会建议,因为虚拟关键字是懒惰加载的.因此,正如我所说,您需要创建基于这些模型的DTO,并仅将DTO发送给客户端.