LINQ query or GetObjectKey to get single Entity Framework entities?

asp.net c# entity-framework linq

Question

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
8
10/24/2011 12:39:15 PM

Accepted Answer

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

9
6/26/2009 4:50:53 PM

Popular Answer

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow