C# 使用 LINQ 查询或 GetObjectKey 检索单个实体框架实体?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1049850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrieve single Entity Framework entities using a LINQ query or GetObjectKey?
提问by John Bubriski
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
与 LINQ
int customerID = 1;
Customer customer = (from c in context.Customers
where c.CustomerID = customerID
select c).FirstOrDefault();
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.
就个人而言,我更喜欢后一种方法,因为要打字。此外,您的 DAL 将相当统一,所有 Get 方法都是查询,尽管这只是个人偏好。
What do you boys and girls use?
男生女生都用什么?
采纳答案by Rob
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.
我更喜欢后者,因为它很清楚你想要什么。通过使用 EntityKey(ADO.NET 团队似乎不理解这一点),我们必须解决实体框架强加给我们的结构。通过以您在第二个示例中所做的方式使用查询语言,我们告诉所有将要查看我们的代码的其他开发人员,嘿,我们只想要这个具有此 ID 的对象,或者我们想要 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. :)
我不认为正确(就像你在第一个例子中一样)是你的同事不清楚的借口。:)
回答by finlay
In my solution, I use generic programming. In the base Repository class I have code like this:
在我的解决方案中,我使用泛型编程。在基本 Repository 类中,我有这样的代码:
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();
}