tags:

views:

986

answers:

4

What are the performance tips that every ADO.NET EF developer should know about?

Please put each tip per answer and explain why the tip is good (e.g. by minimizing DB roundtrips).

+4  A: 

Use ObjectContext#GetObjectByKey() to retrieve entities by their key instead of using First() (or FirstOrDefault) operator in the LINQ query. The latter will hit the database everytime while the former will search the EF cache (ObjectStateManager to be specific) for the entity first and won't hit the database if the entity with the specified key is found.

References

Buu Nguyen
+2  A: 

Assume we have BlogPost entity references User entity via the Author property. Instead of specifying a full User entity to the BlogPost.Author property (which might require a database roundtrip), initializing the reference with the correct EntityKey. For example:

BlogPost.AuthorReference.EntityKey = new EntityKey("EFNamespace.User", "Id", userId);
Buu Nguyen
A: 

A quick and easy way to update detached entity objects. It's an extension method.

public static void AttachUpdated(this ObjectContext obj, EntityObject objectDetached)
{
    if (objectDetached.EntityState == EntityState.Detached)
    {
        object original;
        if (obj.TryGetObjectByKey(objectDetached.EntityKey, out original))
            obj.ApplyPropertyChanges(objectDetached.EntityKey.EntitySetName, objectDetached);
        else
            throw new ObjectNotFoundException();
    }
}
Emil
+2  A: 

A thing I've just learned when profiling the SQLs generated by EF code used in my application: there is a difference between:

IEnumerable<User> users = DB.User.Where(...);
int count = users.Count();

and

IQueryable<User> users = DB.User.Where(...);
int count = users.Count();

The former generates a full query to retrieve matched rows from the User table and the counting is done after the data has been transferred back to EF. The latter does what is generally expected: generate a SELECT COUNT ... SQL, which is much more efficient.

This is quite subtle but not difficult to figure why after noticing about it: it is due to the statically bound nature of C# extension method.

Buu Nguyen