简体   繁体   中英

Entity framework code first many-to-many saving issue

Okay so. I have this. 2 classes. Both with a list of each others items like so:

    public class Bestelling
    {
      public virtual ICollection<Gerecht> Gerechten { get; set; }
    }
    public class Gerecht
    {
    public virtual ICollection<Bestelling> Bestellingen { get; set; }
    }

For simplicity sake I removed the rest of the clutter

Now, in my code those 'gerechten' (sorry for the dutch :D) are added to a particular 'bestelling'. However 'gerechten' with the same ID that are in the list twice (or more) do not get saved, only once.

In a many-to-many relationship in Code First, a composite key will be used between the two separate objects. So, in the intermediate table (which is not necessarily shown to you since you'll use the object model to access your information), you can combine as many Gerecht and Bestellingen as you would like - as long as the combination of the two items are unique (think a composite key). If you try to create additional relationship between Gerecht and Bestellingen, you can do so only if there is another unique identifier. In that case, you should create an additional object along with the appropriate composite keys.

Example (sorry...not familiar with Dutch, so I will use an English example):

public class Person
{
  public int PersonID { get; set; }

  public virtual ICollection<PersonCourse> PersonCourses { get; set; }
}

public class Course
{
  public int CourseID { get; set; }

  public virtual ICollection<PersonCourse> PersonCourses { get; set; }
}

public class PersonCourse
{
  [Key, Column(Order = 0)]
  public int PersonID { get; set; }
  [Key, Column(Order = 1)]
  public int CourseID { get; set; }
  [Key, Column(Order = 2)]
  public int AnotherUniqueParameter { get; set; }

  // Navigation Properties
  public virtual Person { get; set; }
  public virtual Course { get; set; }
}

As long as the combination of the three columns in PersonCourse are unique, you can add as many relationships between a particular Person and Course as you would like. Of course, using this intermediary table is only necessary in this situation. Otherwise, what you've already done is correct (at least from what I can tell based on your question).

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