简体   繁体   English

EF6 多对多表中没有数据

[英]EF6 no data in many-to-many table

I'm learning ASP.NET MVC and EF with Getting Started with EF 6 using MVC 5 tutorial (Contoso University sample application).我正在使用 MVC 5教程(Contoso 大学示例应用程序) 通过 EF 6 入门学习 ASP.NET MVC 和 EF。 It's my first question here, so forgive me if the form of the question isn't perfect (tell me what's wrong anyway).这是我在这里的第一个问题,所以如果问题的形式不完美,请原谅我(无论如何请告诉我有什么问题)。

I've stuck with many to many relation.我一直坚持多对多的关系。 Table is created but no data inside.表已创建,但内部没有数据。

I've added virtual navigation properties to both classes and set mappings in SchoolContext.我已经为这两个类添加了虚拟导航属性,并在 SchoolContext 中设置了映射。

Course.cs课程.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 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 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"));
        }
    } 

Data is initialized in Migrations/Configuration.cs in Seed() method:数据在 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 DbTablesRelationsImage

DbCourseInstructorTableImage DbCourseInstructorTableImage

Here's link to the project on my github if needed: MyGithub如果需要,这里是我 github 上项目的链接: MyGithub

Edit(14:15)编辑(14:15)

I have method in Seed which is assigning Instructors to Courses.我在 Seed 中有一种方法,可以将讲师分配给课程。 But question is why there's still no data in 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));
            }
        }

At no point during seeding are you assigning Instructors to Courses;在播种期间,您绝不会为课程分配讲师; each Course is given an empty List of Instructors.每个课程都有一个空的讲师列表。 So unless this is missing from your question, this is why the many-to-many table is empty.因此,除非您的问题中缺少这一点,否则这就是多对多表为空的原因。

By default navigation properties are not loaded with a query.默认情况下,导航属性不会随查询一起加载。

For example:例如:

using ( var context = new SchoolContext () ) {
    var professor = context.Instructors.FirstOrDefault();
    var courses = professor.Courses // this will be null even if there are linked courses.  
}

To fix this you can use Include().要解决此问题,您可以使用 Include()。

For example:例如:

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.  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM