Add item and update relationship in transitional table in many-to-many database Sql Server

社会主义新天地 提交于 2019-12-12 02:43:53

问题


--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 Properties1 and Properties2 (and update collections of C in existed A and B elements)

I tried many options, like for example this, but still somethings wrong (with ObjectOCntext and existed Key etc)

void SaveNewC(C newC)
{
    using (var context = new MyEntities(connectionString))
    {
        var dbA = context.A.Where(a => a.Id == newC.A.Id).SingleOrDefault();
        var dbB = context.B.Where(b => b.Id == newC.B.Id).SingleOrDefault();

        newC.A = dbA;
        newC.B = dbB;
        context.AddObject(newC);

        context.SaveChanges();
    }
}

EDIT

Exception that I get: "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key."

EDIT2 updated model


回答1:


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



回答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();
    }
}



回答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:

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

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);


来源:https://stackoverflow.com/questions/12354046/add-item-and-update-relationship-in-transitional-table-in-many-to-many-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!