简体   繁体   English

实体框架5多对多

[英]Entity framework 5 many to many

I have problem because when I add the following to class Course I have only 2 tables not 3 我有问题,因为当我在Course添加以下内容时,我只有2个表而不是3个

public int PersonId { get; set; }
[ForeignKey("PersonId")]
public virtual Person Student { get; set; }

you do not have these three lines all good, but I need an additional field in class Course 您没有这三行都很好,但是我在课程课程中需要一个附加字段

public class Person
{
    public int PersonId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public virtual ICollection<Course> CoursesAttending { get; set; }
}

public class Course
{
    public int CourseId { get; set; }
    public string Title { get; set; }
    public int PersonId { get; set; }

        [ForeignKey("PersonId")]
    public virtual Person Student { get; set; }

    public virtual ICollection<Person> Students { get; set; }
}

public class SchoolContext : DbContext
{
    public DbSet<Course> Courses { get; set; }
    public DbSet<Person> People { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        Database.SetInitializer<SchoolContext>(
                new DropCreateDatabaseAlways<SchoolContext>());

        SchoolContext db = new SchoolContext();
        var cos = from d in db.Courses
                  select d;
    }
}

please help me 请帮我

EF cannot decide if Course.Student or Course.Students refers to Person.CoursesAttending . EF无法确定Course.Student还是Course.Students是引用Person.CoursesAttending You must give EF a hint, for example by using the [InverseProperty] attribute on Course.Students : 您必须使用给EF一个提示,例如[InverseProperty]在属性Course.Students

[InverseProperty("CoursesAttending")]
public virtual ICollection<Person> Students { get; set; }

Edit 编辑

The model will cause multiple cascading delete paths, namely: When you delete a Person records in the join table will be deleted as well, but it will also delete all Course s that this person is assigned to through the Course.Person property. 该模型将导致多个级联的删除路径,即:当删除一个PersonCourse.Person表中的记录也将被删除,但是它还将删除此人通过Course.Person属性分配的所有Course The deleted Course s will delete records in the join table again which is the second delete path on the same table. 删除的Course将再次删除联接表中的记录,这是同一表上的第二条删除路径。

Multiple cascading delete paths are not allowed with SQL Server, so you must disable it with Fluent API: SQL Server不允许使用多个级联删除路径,因此必须使用Fluent API禁用它:

public class MyContext : DbContext
{
    //...

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Course>()
            .HasRequired(c => c.Student)
            .WithMany()
            .HasForeignKey(c => c.PersonId)
            .WillCascadeOnDelete(false);
    }
}

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

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