2012-10-18 107 views
0

我正試圖找到一種更有效的方法,以便將其他信息添加到查詢中的列表中。例如,如果我與對象ID和StringA組對象的名單,我想查詢基於對象ID數據庫檢索StringB和StringC:從linq-to-entities查詢向列表中添加附加信息

public class SomeObject { 
    public int ObjectID { get; set; } 
    public string StringA { get; set; } 
    public string StringB { get; set; } 
    public string StringC { get; set; } 
} 

public void AddInformationToSomeObjects(List<SomeObject> someObjects) 
{ 
    var listOfIDs = someObjects.Select(so => so.ObjectID).ToList(); 
    var informationToAdd = db.Table.Where(t => listOfIDs.Contains(t.ObjectID)).Select(t => new { ObjectID = t.ObjectID, StringB = t.StringB, StringC = t.StringC }).ToList(); 

    foreach (var someObject in someObjects) 
    { 
     var information = informationToAdd.Where(i => i.ObjectID == someObject.ObjectID).FirstOrDefault(); 
     someObject.StringB = information.StringB; 
     someObject.StringC = information.StringC; 
    } 
} 

有什麼辦法來查詢合併和分配到一個聲明?

+0

Linq是一種查詢語言 - 它不打算更新實體。看起來你可能會在foreach循環中遇到n + 1問題。如果這就是你想要解決的問題,那麼在迭代它們之前,先在someObjects上做一個.ToList() – Dan

回答

1

剛剛更新了整個List ...

public void AddInformationToSomeObjects(IEnumerable<SomeObject> someObjects) 
{ 
    someObjects = 
     from obj in someObjects 
     join dbObj in db.Table 
     on obj.ObjectID equals dbObj.ObjectID 
     select new SomeObject 
     { 
      ObjectID = obj.ObjectID, 
      StringA = obj.StringA, 
      StringB = dbObj.StringB, 
      StringC = dbObj.StringC 
     } 
} 
0

正如揚P.說,這可能不是一個大問題,只是重新獲取一個新的列表。但是,獲得第一份名單涉及一些昂貴的操作(如獲取斑點),您的想法一點也不差。作爲簡單的加入會做:

public List<SomeObject> AddInformationToSomeObjects(List<SomeObject> someObjects) 
{ 
    var listOfIDs = someObjects.Select(so => so.ObjectID).ToList(); 
    var informationToAdd = db.Table 
     .Where(t => listOfIDs.Contains(t.ObjectID)) 
     .Select(t => new { 
          ObjectID = t.ObjectID, 
          StringB = t.StringB, 
          StringC = t.StringC 
         }).ToList(); 

    return(
     from org in someObjects 
     join a in informationToAdd on org.ObjectID equals a.ObjectID 
     select new SomeObject { 
           ObjectID = org.ObjectID, 
           StringA = org.StringA, 
           StringB = a.StringB, 
           StringC = a.StringC 
          }).ToList(); 
} 

返回一個新的列表,而不是改變原來的僅僅是一個個人喜好(最小化的方法/函數的副作用)。