pun*_*ter 2 c# lazy-loading ef-core-2.1
我按照这里的例子
https://docs.microsoft.com/en-us/ef/core/querying/related-data#lazy-loading
我的两个班级看起来像这样
public class RefMedSchool
{
public int Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public virtual ICollection<ApplicationUser> ApplicationUser { get; set; }
}
public class ApplicationUser : IdentityUser
{
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
public bool MustChangePassword { get; set; }
public int? MedicalSpecialtyId { get; set; }
[ForeignKey("RefMedicalSpecialtyForeignKey")]
public RefMedicalSpecialty RefMedicalSpecialty { get; set; }
public int RefMedSchoolId { get; set; }
public virtual RefMedSchool RefMedSchool { get; set; }
public UserProfileData UserProfileData { get; set; }
public ICollection<UserFeedback> UserFeedbacks { get; set; }
public ICollection<UserAction> UserActions { get; set; }
public ICollection<UserProgram> UserPrograms { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
但是当尝试创建数据库时,我收到以下错误。怎么了 ?这些属性根据需要是虚拟的。
System.InvalidOperationException: 实体类型“ApplicationUser”上的“导航属性”“RefMedicalSpecialty”不是虚拟的。UseLazyLoadingProxies 要求所有实体类型都是公共的、未密封的、具有虚拟导航属性并具有公共或受保护的构造函数。
Entity Framework Core 2.1 引入了延迟加载。它要求所有导航属性都是虚拟的,如问题延迟加载代理:允许指定实体类型/导航中所述:
当前,当使用延迟加载代理时,模型中的每个实体类型都必须适合代理,并且所有导航都必须是虚拟的。这个问题是关于允许某些实体类型/导航延迟加载而其他实体类型/导航则不允许。
问题仍然存在并且没有解决方案,因此仍然不支持您想要的方案。
正如异常告诉你的那样:
UseLazyLoadingProxies 要求所有实体类型都是公共的、未密封的、具有虚拟导航属性并具有公共或受保护的构造函数。
因此,将所有导航属性(即引用其他实体的属性)更改为virtual.
或者ILazyLoader按照Lazy-loading without proxies 中的说明使用:
public class Blog
{
private ICollection<Post> _posts;
public Blog()
{
}
private Blog(ILazyLoader lazyLoader)
{
LazyLoader = lazyLoader;
}
private ILazyLoader LazyLoader { get; set; }
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Post> Posts
{
get => LazyLoader?.Load(this, ref _posts);
set => _posts = value;
}
}
Run Code Online (Sandbox Code Playgroud)