简体   繁体   中英

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

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 . You must give EF a hint, for example by using the [InverseProperty] attribute on 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. The deleted Course s will delete records in the join table again which is the second delete path on the same table.

Multiple cascading delete paths are not allowed with SQL Server, so you must disable it with 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);
    }
}

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.

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