2009-06-26 35 views
8

它看起來像GetObjectKey有搜索現有的,實例化的對象,然後數據存儲的好處。然而,它也好像你失去了一些強類型的,並且需要投下您生成的目標:使用LINQ查詢或GetObjectKey檢索單個實體框架實體?

GetObjectKey

int customerID = 1; 
EntityKey key = new EntityKey("MyEntities.Customers", "CustomerID", customerID); 
Customer customer = context.GetObjectByKey(key) as Customer; 

與LINQ

int customerID = 1; 
Customer customer = (from c in context.Customers 
        where c.CustomerID = customerID 
        select c).FirstOrDefault(); 

就個人而言,我更喜歡後者方法,因爲打字。此外,您的DAL將相當統一,所有Get方法都是查詢,儘管這只是個人偏好。

你男孩和女孩使用什麼?

+0

在前一種方法中,我會使用「as」關鍵字而不是cast。這樣,如果結果爲空,它不會拋出異常。 as關鍵字試圖轉換該值,但如果它不是正確的類型,它會給你null。所以你應該有context.GetObjectByKey(key)作爲Customer ;. – 2009-06-26 15:57:32

回答

9

我更喜歡後者,因爲它清楚地表明你想要什麼。通過使用EntityKey(這是ADO.NET團隊似乎並不瞭解的東西),我們必須解決實體框架強加給我們的結構。通過以第二個示例中的方式使用查詢語言,我們告訴其他所有將查看我們的代碼的開發人員,嘿,我們只是希望使用此ID的此對象或我們希望爲null。

我不認爲這是正確的(因爲你也是第一個例子)是對你的同事不清楚的藉口。 :)

1

在我的解決方案中,我使用泛型編程。在基礎知識庫類中我有這樣的代碼:

private string GetEnittySetName(string entityTypeName) 
{ 
    var container = context.MetadataWorkspace.GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace); 
    string entitySetName = (from meta in container.BaseEntitySets 
          where meta.ElementType.Name == entityTypeName 
          select meta.Name).FirstOrDefault(); 
    return entitySetName; 
} 

private string entitySetName; 

protected string EntitySetName 
{ 
    get 
    { 
     if (string.IsNullOrEmpty(entitySetName)) 
     { 
      entitySetName = GetEnittySetName(typeof(T).Name); 
     } 
     return entitySetName; 
    } 
} 

public T SelectOne(Func<T, bool> exp) 
{ 
    return context.CreateQuery<T>(EntitySetName).Where(exp).FirstOrDefault(); 
}