检索使用LINQ查询或GetObjectKey单一实体框架的实体? [英] Retrieve single Entity Framework entities using a LINQ query or GetObjectKey?

查看:99
本文介绍了检索使用LINQ查询或GetObjectKey单一实体框架的实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看起来GetObjectKey具有搜索现有的实例化对象的利益,然后将数据存储。然而,它也好像你失去了一些强类型的,并需要投你得到的对象:

It looks like GetObjectKey has the benefit of searching for existing, instantiated objects, and THEN the data store. However, it also seems like you lose some of the strong typing, and need to cast your resulting object:

GetObjectKey

GetObjectKey

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

VS。 LINQ

vs. LINQ

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

我个人preFER后一种方法,因为打字。此外,您的DAL将与所有的Get方法是查询相当一致的,虽然这只是一个个人的preference。

Personally, I prefer the latter method, because of the typing. Also, your DAL will be fairly uniform with all of the Get methods being queries, although that's just a personal preference.

你有什么男生和女生使用?

What do you boys and girls use?

推荐答案

我preFER后者,因为它是明确清楚什么是你想要的。通过使用的EntityKey(而这一点是ADO.NET团队似乎并不理解),我们必须解决由实体框架强加给我们的结构。通过在你的第二个例子做的方式使用的查询语言,我们告诉所有的谁永远不会看我们的code开发者的休息,哎,我们只是希望这个ID这个对象还是我们要空。

I prefer the latter because it is explicitly clear what it is you want. By using EntityKey (and this is something that the ADO.NET team doesn't seem to understand), we have to work around the structure imposed on us by Entity Framework. By using the query language in the way you did in the second example, we're telling all of the rest of the developers who will ever look at our code, hey, we just want this object with this ID or we want null.

我不认为这是正确的(如你在第一个例子一样)是不是清楚你的同事的借口。 :)

I don't think that being correct (as you are in the first example as well) is an excuse for not being clear to your colleagues. :)

这篇关于检索使用LINQ查询或GetObjectKey单一实体框架的实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆