我有如下多对多的关系:
Table1
ID (int) | Name (string)
Table2
ID (int) | Data (string)
Table1_2
Table1ID (int) | Table2ID (int)
我想在Entity Framework中执行以下操作:
给定List<Table1>
,查看Table1中是否有匹配的记录;如果是的话,引用它们;如果没有,添加它们并引用它们。例如,像:
public void InsertOrReferenceExisting(string data, List<Table1> table1References)
{
var myEntities = new MyEntities();
var table1Entities = new EntityCollection<Table1>();
foreach(var row in table1References)
{
var existing = myEntities.Table1.Where(x => x.Name == row.Name);
if (existing.Count() > 0)
{
// reference existing row in Table1
}
else
{
// add new row to Table1
}
}
myEntities.Table2.AddObject(new Table2
{
Data = data,
Table1s = table1Entities
});
myEntities.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
}
我是在正确的轨道上吗?
答案 0 :(得分:1)
尝试一下:
public void InsertOrReferenceExisting(string data, List<Table1> table1References)
{
using (var myEntities = new MyEntities())
{
var tbl2 = myEntities.Table2.CreateObject();
tbl2.Data = data;
myEntities.Table2.AddObject(tbl2);
foreach (var row in table1References)
{
var tbl1 = myEntities.Table1.Where(x => x.Name == row.Name).FirstOrDefault();
if (tbl1 == null)
{
tbl1 = myEntities.Table1.CreateObject();
tbl1.Name = row.Name;
}
tbl2.Table1.Add(tbl1);
}
myEntities.SaveChanges();
}
}
请注意,此解决方案不允许Table1中的多个记录在“名称”列中具有相同的值。您可能应该在数据库级别使用唯一约束来强制执行该操作。