简体   繁体   中英

Entity Framework intermediate table - insert new record using existing unrelated ids?

So I have two tables, A and B. Each table is set up like so:

A: ItemAId, ItemAProperty1, ItemAProperty2, etc.
B: ItemBId, ItemBProperty1, ItemBProperty2, etc.

I have a record in table A and a record in table B. These records are in no way related to each other.

I have a third table, C set up like so:

C: ItemAId, ItemBId

I want to make a new record in table C from existing records in tables A and B. C is not available using intellisense. Everywhere I've looked, the suggestion is to build an object from A that already exists, and object(s) from B that already exist, add B to A (or vice versa), then do an add... and because the objects already exist in the database, EF will just do an update and link the objects together in the intermediate table. (From Insert/Update Many to Many Entity Framework . How do I do it? ) IE:

/**** Rough Psuedocode ****/
 var a = context.First(a => a.Id == passedInAId);
 var b = context.First(b => b.Id == passedInBId);
 a.BProperty.Add(b);
 context.Add(a);
 context.SaveChanges()

However, in this case, the objects have no properties that relates them so this is not working.

I know I can write a stored proc to do this, but is it possible to do with EF?

So, as I discovered from digging around some more...

Even though ItemA and ItemB have no direct relations with each other, it appears that the fact that there is a linking table which contains the primary IDs results in an ICollection of ItemA inside the ItemB object, and vice versa. So to get it to work, really all I needed to do was, in fact, get the two objects I wanted to link, add one to the other's collection of said objects, and do an add. Actual (imitation) code of how it works is:

using ( var ctx = new Model()) 
{
   var item1 = ctx.ItemA.FirstOrDefault(i => i.Id == itemAId);
   var item2 = ctx.ItemB.FirstOrDefault(j => j.Id == itemBId);
   item1.ItemBs.Add(item2);
   ctx.SaveChanges();
}

Of course, First() would work if the existence of the objects was already verified, and the "item1.ItemBs.Add()" has "ItemBs" because of EF's annoying tendency to pluralize EVERYTHING.

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