EF6 在多对多 table 中没有数据
EF6 no data in many-to-many table
我正在通过 Getting Started with EF 6 using MVC 5 教程(Contoso 大学示例应用程序)学习 ASP.NET MVC 和 EF。这是我的第一个问题,所以如果问题的形式不完美,请原谅我(无论如何告诉我什么是错的)。
我坚持使用多对多关系。 Table 已创建,但内部没有数据。
我已将虚拟导航属性添加到 类 并在 SchoolContext 中设置映射。
Course.cs
public class Course
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[Display(Name = "Numer")]
public int ID { get; set; }
[StringLength(50, MinimumLength = 3)]
[Display(Name = "Przedmiot")]
public string Title { get; set; }
[Range(0, 5)]
[Display(Name = "ECTS")]
public int Credits { get; set; }
public int DepartmentID { get; set; }
public virtual Department Department { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
public virtual ICollection<Instructor> Instructors { get; set; }
}
Instructor.cs
public class Instructor
{
public int ID { get; set; }
[Required]
[Display(Name = "Nazwisko")]
[StringLength(50)]
public string LastName { get; set; }
[Required]
[Column("FirstMidName")]
[Display(Name = "Imię")]
[StringLength(50)]
public string FirstName { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Data zatrudnienia")]
public DateTime HireDate { get; set; }
public string FullName
{
get
{
return LastName + " " + FirstName;
}
}
public virtual ICollection<Course> Courses { get; set; }
public virtual OfficeAssignment OfficeAssignment { get; set; }
}
SchoolContext.cs
public class SchoolContext : DbContext
{
public SchoolContext() : base("SchoolContext")
{
}
public DbSet<Course> Courses { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<Instructor> Instructors { get; set; }
public DbSet<Student> Students { get; set; }
public DbSet<OfficeAssignment> OfficeAssignments { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Course>()
.HasMany(c => c.Instructors).WithMany(i => i.Courses)
.Map(t => t.MapLeftKey("CourseID")
.MapRightKey("InstructorID")
.ToTable("CourseInstructor"));
}
}
数据在 Migrations/Configuration.cs 中的 Seed() 方法中初始化:
protected override void Seed(MyUniversity.DAL.SchoolContext context)
{ (...)
var instructors = new List<Instructor>
{
new Instructor { FirstName = "Antoni", LastName = "Czerwiński", HireDate = DateTime.Parse("2016-07-01")},
new Instructor { FirstName = "Czesław", LastName = "Piotrowski", HireDate = DateTime.Parse("2016-07-01")},
new Instructor { FirstName = "Paweł", LastName = "Andrzejewski", HireDate = DateTime.Parse("2016-07-01")},
new Instructor { FirstName = "Karol", LastName = "Sokołowski", HireDate = DateTime.Parse("2016-07-01")},
new Instructor { FirstName = "Alojzy", LastName = "Woźniak", HireDate = DateTime.Parse("2016-07-01")}
};
instructors.ForEach(s => context.Instructors.AddOrUpdate(p => p.LastName, s));
context.SaveChanges();
var courses = new List<Course>
{
new Course { ID = 1050, Title = "Chemia", Credits =3,
DepartmentID = departments.Single(s => s.Name == "Inżynierii").ID, Instructors = new List<Instructor>() },
new Course { ID = 4022, Title = "Mikroekonomia", Credits =3,
DepartmentID = departments.Single(s => s.Name == "Ekonomiczny").ID, Instructors = new List<Instructor>() },
new Course { ID = 4041, Title = "Makroekonomia", Credits =3,
DepartmentID = departments.Single(s => s.Name == "Ekonomiczny").ID, Instructors = new List<Instructor>() },
new Course { ID = 1045, Title = "Rachunek Różniczkowy", Credits =4,
DepartmentID = departments.Single(s => s.Name == "Matematyki").ID, Instructors = new List<Instructor>() },
new Course { ID = 3141, Title = "Trygonometria", Credits =4,
DepartmentID = departments.Single(s => s.Name == "Matematyki").ID, Instructors = new List<Instructor>() },
new Course { ID = 2021, Title = "Kompozycja", Credits =3,
DepartmentID = departments.Single(s => s.Name == "Anglistyki").ID, Instructors = new List<Instructor>() },
new Course { ID = 2042, Title = "Literatura", Credits =4,
DepartmentID = departments.Single(s => s.Name == "Anglistyki").ID, Instructors = new List<Instructor>() }
};
courses.ForEach(s => context.Courses.AddOrUpdate(p => p.ID, s));
context.SaveChanges();
(...)
}
DbTablesRelationsImage
DbCourseInstructorTableImage
如果需要的话,这里 link 到我的 github 上的项目:MyGithub
编辑(14:15)
我在 Seed 中有一种方法,可以将讲师分配给课程。
但是问题是为什么table里面还是没有数据?
protected override void Seed(MyUniversity.DAL.SchoolContext context)
{ (...)
AddOrUpdateInstructor(context, "Chemia", "Sokołowski");
AddOrUpdateInstructor(context, "Chemia", "Andrzejewski");
AddOrUpdateInstructor(context, "Mikroekonomia", "Woźniak");
AddOrUpdateInstructor(context, "Makroekonomia", "Woźniak");
AddOrUpdateInstructor(context, "Rachunek Różniczkowy", "Piotrowski");
AddOrUpdateInstructor(context, "Trygonometria", "Andrzejewski");
AddOrUpdateInstructor(context, "Kompozycja", "Czerwiński");
AddOrUpdateInstructor(context, "Literatura", "Czerwiński");
context.SaveChanges();
}
void AddOrUpdateInstructor(SchoolContext context, string courseTitle, string instructorName)
{
var crs = context.Courses.SingleOrDefault(c => c.Title ==
courseTitle);
var inst = context.Instructors.SingleOrDefault(i => i.LastName ==
instructorName);
if (inst == null)
{
crs.Instructors.Add(context.Instructors.Single(i => i.LastName ==
instructorName));
}
}
在播种期间,您绝不会为课程分配讲师;每个课程都有一个空的讲师列表。因此,除非您的问题中缺少这一点,否则这就是多对多 table 为空的原因。
默认情况下,导航属性不加载查询。
例如:
using ( var context = new SchoolContext () ) {
var professor = context.Instructors.FirstOrDefault();
var courses = professor.Courses // this will be null even if there are linked courses.
}
要解决此问题,您可以使用 Include()。
例如:
using ( var context = new SchoolContext () ) {
var professor = context.Instructors
// this instructs EF to do the Join operation and include the Courses navigation property.
.Include ( prof => prof.Courses )
.FirstOrDefault();
var courses = professor.Courses // this will now be populated with courses.
}
我正在通过 Getting Started with EF 6 using MVC 5 教程(Contoso 大学示例应用程序)学习 ASP.NET MVC 和 EF。这是我的第一个问题,所以如果问题的形式不完美,请原谅我(无论如何告诉我什么是错的)。
我坚持使用多对多关系。 Table 已创建,但内部没有数据。
我已将虚拟导航属性添加到 类 并在 SchoolContext 中设置映射。
Course.cs
public class Course
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[Display(Name = "Numer")]
public int ID { get; set; }
[StringLength(50, MinimumLength = 3)]
[Display(Name = "Przedmiot")]
public string Title { get; set; }
[Range(0, 5)]
[Display(Name = "ECTS")]
public int Credits { get; set; }
public int DepartmentID { get; set; }
public virtual Department Department { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
public virtual ICollection<Instructor> Instructors { get; set; }
}
Instructor.cs
public class Instructor
{
public int ID { get; set; }
[Required]
[Display(Name = "Nazwisko")]
[StringLength(50)]
public string LastName { get; set; }
[Required]
[Column("FirstMidName")]
[Display(Name = "Imię")]
[StringLength(50)]
public string FirstName { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Data zatrudnienia")]
public DateTime HireDate { get; set; }
public string FullName
{
get
{
return LastName + " " + FirstName;
}
}
public virtual ICollection<Course> Courses { get; set; }
public virtual OfficeAssignment OfficeAssignment { get; set; }
}
SchoolContext.cs
public class SchoolContext : DbContext
{
public SchoolContext() : base("SchoolContext")
{
}
public DbSet<Course> Courses { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<Instructor> Instructors { get; set; }
public DbSet<Student> Students { get; set; }
public DbSet<OfficeAssignment> OfficeAssignments { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Course>()
.HasMany(c => c.Instructors).WithMany(i => i.Courses)
.Map(t => t.MapLeftKey("CourseID")
.MapRightKey("InstructorID")
.ToTable("CourseInstructor"));
}
}
数据在 Migrations/Configuration.cs 中的 Seed() 方法中初始化:
protected override void Seed(MyUniversity.DAL.SchoolContext context)
{ (...)
var instructors = new List<Instructor>
{
new Instructor { FirstName = "Antoni", LastName = "Czerwiński", HireDate = DateTime.Parse("2016-07-01")},
new Instructor { FirstName = "Czesław", LastName = "Piotrowski", HireDate = DateTime.Parse("2016-07-01")},
new Instructor { FirstName = "Paweł", LastName = "Andrzejewski", HireDate = DateTime.Parse("2016-07-01")},
new Instructor { FirstName = "Karol", LastName = "Sokołowski", HireDate = DateTime.Parse("2016-07-01")},
new Instructor { FirstName = "Alojzy", LastName = "Woźniak", HireDate = DateTime.Parse("2016-07-01")}
};
instructors.ForEach(s => context.Instructors.AddOrUpdate(p => p.LastName, s));
context.SaveChanges();
var courses = new List<Course>
{
new Course { ID = 1050, Title = "Chemia", Credits =3,
DepartmentID = departments.Single(s => s.Name == "Inżynierii").ID, Instructors = new List<Instructor>() },
new Course { ID = 4022, Title = "Mikroekonomia", Credits =3,
DepartmentID = departments.Single(s => s.Name == "Ekonomiczny").ID, Instructors = new List<Instructor>() },
new Course { ID = 4041, Title = "Makroekonomia", Credits =3,
DepartmentID = departments.Single(s => s.Name == "Ekonomiczny").ID, Instructors = new List<Instructor>() },
new Course { ID = 1045, Title = "Rachunek Różniczkowy", Credits =4,
DepartmentID = departments.Single(s => s.Name == "Matematyki").ID, Instructors = new List<Instructor>() },
new Course { ID = 3141, Title = "Trygonometria", Credits =4,
DepartmentID = departments.Single(s => s.Name == "Matematyki").ID, Instructors = new List<Instructor>() },
new Course { ID = 2021, Title = "Kompozycja", Credits =3,
DepartmentID = departments.Single(s => s.Name == "Anglistyki").ID, Instructors = new List<Instructor>() },
new Course { ID = 2042, Title = "Literatura", Credits =4,
DepartmentID = departments.Single(s => s.Name == "Anglistyki").ID, Instructors = new List<Instructor>() }
};
courses.ForEach(s => context.Courses.AddOrUpdate(p => p.ID, s));
context.SaveChanges();
(...)
}
DbTablesRelationsImage
DbCourseInstructorTableImage
如果需要的话,这里 link 到我的 github 上的项目:MyGithub
编辑(14:15)
我在 Seed 中有一种方法,可以将讲师分配给课程。 但是问题是为什么table里面还是没有数据?
protected override void Seed(MyUniversity.DAL.SchoolContext context)
{ (...)
AddOrUpdateInstructor(context, "Chemia", "Sokołowski");
AddOrUpdateInstructor(context, "Chemia", "Andrzejewski");
AddOrUpdateInstructor(context, "Mikroekonomia", "Woźniak");
AddOrUpdateInstructor(context, "Makroekonomia", "Woźniak");
AddOrUpdateInstructor(context, "Rachunek Różniczkowy", "Piotrowski");
AddOrUpdateInstructor(context, "Trygonometria", "Andrzejewski");
AddOrUpdateInstructor(context, "Kompozycja", "Czerwiński");
AddOrUpdateInstructor(context, "Literatura", "Czerwiński");
context.SaveChanges();
}
void AddOrUpdateInstructor(SchoolContext context, string courseTitle, string instructorName)
{
var crs = context.Courses.SingleOrDefault(c => c.Title ==
courseTitle);
var inst = context.Instructors.SingleOrDefault(i => i.LastName ==
instructorName);
if (inst == null)
{
crs.Instructors.Add(context.Instructors.Single(i => i.LastName ==
instructorName));
}
}
在播种期间,您绝不会为课程分配讲师;每个课程都有一个空的讲师列表。因此,除非您的问题中缺少这一点,否则这就是多对多 table 为空的原因。
默认情况下,导航属性不加载查询。
例如:
using ( var context = new SchoolContext () ) {
var professor = context.Instructors.FirstOrDefault();
var courses = professor.Courses // this will be null even if there are linked courses.
}
要解决此问题,您可以使用 Include()。
例如:
using ( var context = new SchoolContext () ) {
var professor = context.Instructors
// this instructs EF to do the Join operation and include the Courses navigation property.
.Include ( prof => prof.Courses )
.FirstOrDefault();
var courses = professor.Courses // this will now be populated with courses.
}