C# 延迟加载EF Core 2.1不使用标识?
我在这里遵循了这个例子 我的两门课是这样的C# 延迟加载EF Core 2.1不使用标识?,c#,lazy-loading,ef-core-2.1,C#,Lazy Loading,Ef Core 2.1,我在这里遵循了这个例子 我的两门课是这样的 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 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; }
}
公立学校
{
公共int Id{get;set;}
公共字符串代码{get;set;}
公共字符串名称{get;set;}
公共虚拟ICollection应用程序用户{get;set;}
}
公共类应用程序用户:IdentityUser
{
公共字符串UserFirstName{get;set;}
公共字符串UserLastName{get;set;}
公共bool MustChangePassword{get;set;}
公共int?MedicalSpecialtyId{get;set;}
[ForeignKey(“RefMedicalSpecialForeignKey”)]
public RefMedicalSpecialty RefMedicalSpecialty{get;set;}
public int RefMedSchoolId{get;set;}
公共虚拟参考医学院参考医学院{get;set;}
public UserProfileData UserProfileData{get;set;}
公共ICollection用户反馈{get;set;}
公共ICollection用户操作{get;set;}
公共ICollection用户程序{get;set;}
}
但是当试图创建数据库时,我得到了下面的错误。怎么了?属性根据需要是虚拟的
System.InvalidOperationException:实体类型“ApplicationUser”上的导航属性“RefMedicalSpecial”不是虚拟的。UseLazyLoadingProxies要求所有实体类型都是公共的、未密封的、具有虚拟导航属性,并且具有公共或受保护的构造函数。”
实体框架核心2.1引入了延迟加载。它要求所有导航属性都是虚拟的,如问题中所述: 当前,当使用延迟加载代理时,模型中的每个实体类型都必须适合代理,并且所有导航都必须是虚拟的。此问题是关于允许延迟加载某些实体类型/导航,而不允许延迟加载其他实体类型/导航 问题仍然存在,没有解决方案,因此仍然不支持您想要的方案 例外情况告诉你: UseLazyLoadingProxies要求所有实体类型都是公共的、未密封的、具有虚拟导航属性,并且具有公共或受保护的构造函数 因此,将所有导航属性(即引用其他实体的属性)更改为
virtual
或者使用ILazyLoader
,如中所述:
公共类博客
{
私人I收集站;
公共博客()
{
}
私人博客(ILazyLoader lazyLoader)
{
懒汉=懒汉;
}
私有ILazyLoader LazyLoader{get;set;}
公共int Id{get;set;}
公共字符串名称{get;set;}
公共收集站
{
get=>LazyLoader?.Load(这是参考文章);
set=>\u posts=value;
}
}
Ok。我的错误是认为我可以只指定一个我想要延迟加载的特定属性,并且只使其成为虚拟的。如果我想取消延迟加载,我需要删除所有虚拟访问修饰符吗?或者有更简单的方法吗?
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;
}
}