I'm using Entity Framework Core in context of a ASP.Net Core MVC application. 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). This is quite handy to be used in ASP.Net. Is there any similar concept for the to-many-reference Students
?
At the end I would like to create a multi-select in ASP.Net. Hence, I need a list of IDs of assigned Students
to this seminar.
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. That is assuming that Person
has a foreign key for 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. Refer to this for more info
You can do it by fluent api
modelBuilder.Entity<Seminars>()
.HasMany(c => c.Students)
.WithOptional()
.Map(m => m.MapKey("StudentId"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.