【发布时间】:2009-06-26 15:44:02
【问题描述】:
看起来 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”关键字而不是强制转换。这样,如果结果为 null,则不会引发异常。 as 关键字尝试强制转换值,但如果它不是正确的类型,它会给你 null 。所以你会有 context.GetObjectByKey(key) as Customer;.
-
好点。我将修改示例以使分数更均匀。
标签: c# asp.net linq entity-framework