我按照这里的例子
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; }
}
但是,当尝试创建数据库时,出现以下错误。怎么了 ?这些属性根据需要是虚拟的。
System.InvalidOperationException:实体类型'ApplicationUser'上的'导航属性'RefMedicalSpecialty'不是虚拟的。 UseLazyLoadingProxies要求所有实体类型都是公共的,未密封的,具有虚拟导航属性以及公共或受保护的构造函数。
最佳答案
实体框架核心2.1引入了延迟加载。它要求所有导航属性都是虚拟的,如问题Lazy-loading proxies: allow entity types/navigations to be specified中所述:
当前,当使用延迟加载代理时,模型中的每种实体类型都必须适合代理,并且所有导航都必须是虚拟的。此问题是关于允许某些实体类型/导航被延迟加载而其他实体则不是。
该问题仍未解决,无法解决,因此仍不支持您所需的方案。
异常告诉您:
UseLazyLoadingProxies要求所有实体类型都是公共的,未密封的,具有虚拟导航属性以及公共或受保护的构造函数。
因此,将所有导航属性(即引用其他实体的属性)更改为virtual
。
或按照Lazy-loading without proxies中的说明使用ILazyLoader
:
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;
}
}
关于c# - 延迟加载EF Core 2.1是否不能与Identity一起使用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50722475/