[英]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和B。每个表的设置如下:
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. 我在表A中有一条记录,在表B中有一条记录。这些记录之间没有任何关联。
I have a third table, C set up like so: 我有第三个表,C设置如下:
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. 我想根据表A和B中的现有记录在表C中创建新记录。使用智能感知无法使用C。 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.
我到过的任何地方,建议是从已经存在的A构造一个对象,然后从已经存在的B构造一个对象,将B添加到A(反之亦然),然后执行添加...,因为数据库中已经存在对象,EF只会进行更新并将对象链接到中间表中。 (From Insert/Update Many to Many Entity Framework . How do I do it? ) IE:
(从插入/更新多实体实体到多实体实体。我该怎么做? )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? 我知道我可以编写一个存储的proc来做到这一点,但是可以使用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. 即使ItemA和ItemB之间没有直接关系,但似乎存在一个包含主ID的链接表这一事实,会在ItemB对象内导致ItemA的ICollection,反之亦然。 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. 当然,如果已经验证了对象的存在,则First()将起作用,并且由于EF烦人的使所有内容都复数化的趋势,“ item1.ItemBs.Add()”具有“ ItemBs”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.