Skip to content Skip to sidebar Skip to footer

Add Item And Update Relationship In Transitional Table In Many-to-many Database Sql Server

--here was wrong model without association manyTOmany between A-B. corrected is in EDIT2-- A exists in database, B exists in database. I need only enter new C element with some Pro

Solution 1:

context.Entry(dbA).State = EntityState.Unchanged;
context.Entry(dbB).State = EntityState.Unchanged;
context.AddObject(newC);
context.SaveChanges();

Solution 2:

Apparently your newC has already populated navigation properties A and B with the correct Ids. Then you can just attach the entities refered by the navigation properties to the context:

void SaveNewC(C newC)
{
    using (var context = new MyEntities(connectionString))
    {
        context.A.Attach(newC.A);
        context.B.Attach(newC.B);

        context.C.AddObject(newC);

        context.SaveChanges();
    }
}

Solution 3:

Do you need to have the junction table mapped? If all your wanting is a Many to Many from A->B you could do it in a simpler way.

If you created the C table as a true junction - and have a FK to A and B set to it's PK in sql like this:

enter image description here

Then when you create your edmx from the model it will create this:

enter image description here

Now, in your code if you wanted to add a relationship, you would simply add it to your collection, and EF will automatically create the relationship in your C table for you:

var A = new A();
        var b = new B();
        var b2 = new B();

        A.B.Add(b);
        A.B.Add(b2);

Post a Comment for "Add Item And Update Relationship In Transitional Table In Many-to-many Database Sql Server"