Retrieve single Entity Framework entities using a

2020-06-17 04:36发布

问题:

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

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

vs. 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.

What do you boys and girls use?

回答1:

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. :)



回答2:

In my solution, I use generic programming. In the base Repository class I have code like this:

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