EF实体类种的Virtual关键字作用

原文: EF实体类种的Virtual关键字作用

在使用EF中我们会使用导航属性,其中会加上Virtual关键字,这个有什么作用呢。加了此关键字就可以使用lazyload懒加载,不加此特性的话是加载不出此导航属性的内容的。

例子,有两个实体sys_user 和 sys_dep


  
  
  1. public partial class sys_user
  2. {
  3. [ Key]
  4. [ StringLength(50)]
  5. public string account { get; set; }
  6. [ StringLength(50)]
  7. public string name { get; set; }
  8. [ StringLength(50)]
  9. public string password { get; set; }
  10. public int? age { get; set; }
  11. [ StringLength(50)]
  12. public string sex { get; set; }
  13. [ StringLength(50)]
  14. public string depid { get; set; }
  15. [ StringLength(50)]
  16. public string status { get; set; }
  17. [ StringLength(50)]
  18. public string roleid { get; set; }
  19. public virtual sys_dep sys_dep { get; set; }
  20. }

  
  
  1. public partial class sys_dep
  2. {
  3. [ Key]
  4. [ StringLength(50)]
  5. public string depid { get; set; }
  6. [ StringLength(50)]
  7. public string depname { get; set; }
  8. [ StringLength(50)]
  9. public string manager { get; set; }
  10. }

  
  
  1. using (oaEntities db = new oaEntities()) {
  2. db.Database.Log = s => { Console.WriteLine(s); };
  3. var q = db.sys_user.Select(b => b);
  4. foreach ( var item in q) {
  5. Console.WriteLine( $"User Show:{item.account},{item.name},{item.sys_dep.depname}");
  6. }
  7. }

可以看到将sys_dep的depname信息显示出来了

下面我们把Virtual关键字拿掉改为        public sys_dep sys_dep { get; set; }

重新运行后就会出现如此错误了

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/12920527.html
今日推荐