多对一是一种很常见的关系,例如:一个班级有一个学生集合属性,同时,班级有班长、语文课代表、数学课代表等单个学生属性,如果定义2个实体类,班级SchoolClass和学生Student,那么,班级SchoolClass类有多个学生Student类的导航属性,学生Student类有一个班级SchoolClass类的导航属性。此时就需要使用InverseProperty反向导航属性去指定通过哪个属性建立引用关系,否则数据库建不起来。
通过一个小DEMO做试验。
新建Asp.Net Core MVC网站项目,添加2个实体类如下所示
//班级
public class SchoolClass
{
//主键
public int ID { get; set; }
//班级名字
public string ClassTitle { get; set; }
//本班级的学生集合
public List<Student> Students { get; set; }
//班长
public Student ClassMonitor { get; set; }
//语文课代表
public Student Chinese { get; set; }
//数学课代表
public Student Mathematics { get; set; }
}
//学生
public class Student
{
//主键
public int ID { get; set; }
//姓名
public string Name { get; set; }
//学生所在的班级
public SchoolClass MyClass { get; set; }
}
然后通过右键菜单添加SchoolClass实体类的控制器,让系统自动创建数据库上下文代码
然后会收到一个错误。
Unable to determine the relationship represented by navigation property 'SchoolClass.Students' of type 'List<Student>'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'. StackTrace:
系统无法判断SchoolClass多个Student导航属性的关系,此时可以在Students属性上面添加反向导航属性[InverseProperty("MyClass")],就可以完成自动化创建控制器了。
[InverseProperty("MyClass")]
public List<Student> Students { get; set; }
然后在软件启动时创建一组测试数据。
public static void Main(string[] args)
{
//CreateWebHostBuilder(args).Build().Run();
IWebHost webHost = CreateWebHostBuilder(args).Build();
//系统初始化
AppInit(webHost.Services);
webHost.Run();
}
//系统初始化
private static void AppInit(IServiceProvider serviceProvider)
{
//初始化数据库
using (var scope = serviceProvider.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<StudentWebContext>();
//确保创建数据库
context.Database.EnsureCreated();
if (context.SchoolClass.Any())
return;
var schoolClass61 = new SchoolClass()
{
ClassTitle = "六一班"
};
//先保存班级,否则报错