[英]Entity Framework Core foreign keys many
I'm using Entity Framework Core in context of a ASP.Net Core MVC application. 我在ASP.Net Core MVC应用程序的上下文中使用Entity Framework Core。 A snippet of the data model looks like that:
数据模型的片段如下所示:
public class Seminar
{
public int ID { get; set; }
public string Name { get; set; }
public Person Teacher { get; set; }
public int TeacherID { get; set; }
public IList<Person> Students { get; set; }
public Seminar()
{
Students = new List<Person>();
}
}
EF automatically assigns the property TeacherID
to reflect the ID of the entity Teacher
(foreign key). EF自动分配属性
TeacherID
以反映实体Teacher
的ID(外键)。 This is quite handy to be used in ASP.Net. 这在ASP.Net中使用非常方便。 Is there any similar concept for the to-many-reference
Students
? 有很多推荐
Students
有类似的概念吗?
At the end I would like to create a multi-select in ASP.Net. 最后,我想在ASP.Net中创建一个多选。 Hence, I need a list of IDs of assigned
Students
to this seminar. 因此,我需要一份分配给该研讨会的
Students
ID的列表。
EF will infer the one-to-many relationship thanks to the IList<Person> Students
navigation property, and it will refer to Students with that name. 借助
IList<Person> Students
导航属性,EF将推断出一对多关系,并且它将引用具有该名称的Student。 That is assuming that Person
has a foreign key for Seminar
. 假设
Person
具有Seminar
的外键。 But then Person
should also have a foreign key for seminar as a Teacher, so in the end that should be a many-to-many reationship, which requires a fluent API definition. 但是然后,
Person
还应该以教师的身份为研讨会提供外键,因此最终应该是多对多的关系,这需要流畅的API定义。 Refer to this for more info 参考此以获取更多信息
You can do it by fluent api 你可以通过流利的API做到这一点
modelBuilder.Entity<Seminars>()
.HasMany(c => c.Students)
.WithOptional()
.Map(m => m.MapKey("StudentId"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.