c# – 实体框架循环引用

前端之家收集整理的这篇文章主要介绍了c# – 实体框架循环引用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
再次尝试这个问题,因为我的第一次尝试几乎没有一致:p

所以我超级混淆,并使用实体框架代码第一

我有森林课.

我有一个树类.

每个森林都可以有很多树木

当我试图序列化我正在获得循环引用

  1. public class Forest
  2. {
  3.  
  4. public Guid ID { get; set; }
  5. public virtual List<Tree> Trees { get; set; }
  6. }
  7. public class Tree
  8. {
  9. public Guid ID { get; set; }
  10. public Guid? ForestId {get;set;}
  11.  
  12. [ForeignKey("ForestId")]
  13. public virtual Forest Forest {get;set;}
  14. }

每个森林都有树木,但并不是每棵树都在森林里.在进行多重性的错误时,我会遇到困难

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

模型是森林的地方

如果我将ForestId作为Guid而不是Guid?我收到循环引用错误.

我也试过
保护覆盖void

  1. OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
  2. {
  3. modelBuilder.Entity<Forest>()
  4. .HasMany(x => x.Tree)
  5. .WithOptional()
  6. .HasForeignKey(y => y.ForestId);
  7. }

提前致谢

解决方法

最好的方法是您应该使用DTO将您想要的数据传输到客户端. DTO应该具有简单的属性,因此不会创建循环引用错误.目前森林里有“树”和“树”树木和树木中的每棵树都有森林,那个森林里又有“树”和“树”.

要么

您可以使用ScriptIgnore来修饰您不需要的属性属性
Json.Encode进行序列化,然后不会发送回客户端.

http://msdn.microsoft.com/en-us/library/system.web.script.serialization.scriptignoreattribute.aspx

例如:

  1. public class Forest
  2. {
  3. public Guid ID { get; set; }
  4. public virtual List<Tree> Trees { get; set; }
  5. }
  6. public class Tree
  7. {
  8. public Guid ID { get; set; }
  9. public Guid? ForestId {get;set;}
  10.  
  11. [ForeignKey("ForestId")]
  12. [ScriptIgnore]
  13. public virtual Forest Forest {get;set;}
  14. }

编辑:

除了ScriptIgnore之外,您还应该从Forest和Trees中删除虚拟机,这样就可以运行.我已经测试了但是,我不会建议,因为虚拟关键字是懒惰加载的.因此,正如我所说,您需要创建基于这些模型的DTO,并仅将DTO发送给客户端.

猜你在找的C#相关文章