它看起來像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方法都是查詢,儘管這只是個人偏好。
你男孩和女孩使用什麼?
在前一種方法中,我會使用「as」關鍵字而不是cast。這樣,如果結果爲空,它不會拋出異常。 as關鍵字試圖轉換該值,但如果它不是正確的類型,它會給你null。所以你應該有context.GetObjectByKey(key)作爲Customer ;. – 2009-06-26 15:57:32