简体   繁体   中英

Ef6, Many to many, Inserts and Primary keys

I have a problem with populating the right values in a junction table for a many to many relationship. In the image below I have simplified what I am trying to do. The "Table on the left" has values in the database that I want to use. The table of the right is about to receive new records. It has a navigation property to the Junction table and the same is true for the table on the left. The junction table has navigation properties to both tables on its rear and they are set to required .

在此处输入图片说明

When I create the new records in the table on the right, I also add to it records in the junction table. The TOL_ID is known as it is saved in the database, but the TOR_ID is about to be created, therefore unknown. When I attempt to call the SaveChanges in my context, it tries to save the junction table records first, before the TOR_IDs have been populated for the record on the right. I though that marking the navigation property as Required would make the EF understand that TOR_ID must exist before creating the junction table row. Instead it tries to insert an existing TOL_ID and 0, which gives a violation when trying to insert many table on the right records connected to the same TOL_ID.

Note: Saving the TOR_IDs first and then connecting with junction records is not an option, as the creation of the junction table records are part of a " Slowly changing dimension " type 6 flow.

This is how it really looks like in the code:

// The newRating is the new object corresponding the Table on the right
var newRating = new ModuleRating() 
{ 
    // The moduleRating.RatedDriveUnit already exists in the db
    RatedDriveUnit = moduleRating.RatedDriveUnit 
};

newModule.Ratings.Add(newRating);

If you follow the Code First below classes will helpful

public class TOL
{
    [Key]
    public int TOL_ID { get; set; }
    public int Col1 { get; set; }

    public ICollection<TOR> Tors { get; set; }
}

public class TOR
{
    [Key]
    public int TOR_ID { get; set; }
    public int Col1 { get; set; }

    public ICollection<TOL> Tols { get; set; }
}

public class TolTorContext : DbContext
{
    public DbSet<TOL> Tols { get; set; }
    public DbSet<TOR> Tors { get; set; }
}  

If you follow database first approach,make FK at Join Table and try to chhange id names TOLId , TORId

I'am sorry for spending your time. After some investigation I noticed that the supposed composite unique index (TOL_ID and TOR_ID) of the junction table had been set wrong. Instead two separate unique indexes had been applied to TOL_ID and TOR_ID, which resulted a constrain violation as soon as one of those two values appeared twice.

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