LINQ query or GetObjectKey to get single Entity Framework entities?

asp.net c# entity-framework linq

Question

GetObjectKey seems to have the advantage of looking for already-instantiated objects and THEN the data storage. It also seems that you lose part of the strong type and must cast your object as a result:

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

Due to the typing, I like the latter approach myself. With all of the Get methods being queries, your DAL will also be quite consistent, though this is just a matter of desire.

What tools do you men and women use?

1
8
10/24/2011 12:39:15 PM

Accepted Answer

The latter is better in my opinion since it makes what you want very clear. We have to get around the structure that Entity Framework imposes on us by utilizing EntityKey (and the ADO.NET team doesn't appear to comprehend this). By using the query language in the second example's manner, we are informing any other developers who may ever look at our code that we only want this object with this ID or null.

Being accurate (as you are in the first case as well) is not a justification for being unclear to your coworkers, in my opinion.

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

Popular Answer

I use generic programming into my solution. I have the following code in the basic Repository class:

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