在使用EF中我们会使用导航属性,其中会加上Virtual关键字,这个有什么作用呢。加了此关键字就可以使用lazyload懒加载,不加此特性的话是加载不出此导航属性的内容的。
例子,有两个实体sys_user 和 sys_dep
- public partial class sys_user
- {
- [Key]
- [StringLength(50)]
- public string account { get; set; }
-
- [StringLength(50)]
- public string name { get; set; }
-
- [StringLength(50)]
- public string password { get; set; }
-
- public int? age { get; set; }
-
- [StringLength(50)]
- public string sex { get; set; }
-
- [StringLength(50)]
- public string depid { get; set; }
-
- [StringLength(50)]
- public string status { get; set; }
-
- [StringLength(50)]
- public string roleid { get; set; }
- public virtual sys_dep sys_dep { get; set; }
- }
- public partial class sys_dep
- {
- [Key]
- [StringLength(50)]
- public string depid { get; set; }
-
- [StringLength(50)]
- public string depname { get; set; }
-
- [StringLength(50)]
- public string manager { get; set; }
- }
- using (oaEntities db = new oaEntities()) {
- db.Database.Log = s => { Console.WriteLine(s); };
- var q = db.sys_user.Select(b => b);
- foreach (var item in q) {
- Console.WriteLine($"User Show:{item.account},{item.name},{item.sys_dep.depname}");
- }
- }
可以看到将sys_dep的depname信息显示出来了
下面我们把Virtual关键字拿掉改为 public sys_dep sys_dep { get; set; }
重新运行后就会出现如此错误了
原文:https://www.cnblogs.com/lonelyxmas/p/12920527.html