简体   繁体   English

使用LINQ查询或GetObjectKey检索单个Entity Framework实体?

[英]Retrieve single Entity Framework entities using a LINQ query or GetObjectKey?

It looks like GetObjectKey has the benefit of searching for existing, instantiated objects, and THEN the data store. 看起来GetObjectKey具有搜索现有的实例化对象以及数据存储的好处。 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? 你们男孩和女孩用的是什么?

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. 通过使用EntityKey(这是ADO.NET团队似乎无法理解的东西),我们必须解决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. 通过在第二个示例中使用查询语言,我们告诉所有其他开发人员,他们将查看我们的代码,嘿,我们只是希望这个对象具有此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. 我不认为这是正确的(正如你在第一个例子中所说的那样)是一个不向同事说清楚的借口。 :) :)

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM