2012-02-06 95 views
0

關係我有很多一對多的關係如下:參考現有記錄或添加新記錄許多一對多在EF

Table1 
ID (int) | Name (string) 

Table2 
ID (int) | Data (string) 

Table1_2 
Table1ID (int) | Table2ID (int) 

我願做實體框架如下:

給定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

你爲什麼要在table2中添加table1Entities? – 2012-02-06 20:35:13

+0

澄清:您的最終目標是保存新的Table1對象,即新的Table2對象,並在Table1_2表中爲新的Table2記錄和每個Table1記錄傳入(新的或不是)。 – 2012-02-06 20:40:49

+0

@JasonWilliams:對 – cm007 2012-02-06 20:53:00

回答

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

請注意,此解決方案不允許在表1的多個記錄那些在名稱列中的值相同。您應該在數據庫級別上使用唯一約束來強制執行該操作。