An Improved Entity Framework Tip for EF4 thanks to Zeeshan

In my EF Tips & Tricks talk that I just did at DevConnections, I have a suggestion to reduce redundant methods where you might expose queries to generate reference lists.


static List<CustomerType> CustomerTypeList(MyEntities context)
    return context.CustomerTypes.OrderBy(ct => ct.Type).ToList();

static List<States> StatesList(MyEntities context)
    return context.States.OrderBy(ct => ct.StateName).ToList();

Instead I have a single generic method, GetRefernenceList<TEntity> that uses some tricks with Entity SQL and MetadataWorkspace  to dynamically build the query and return the requested list.

This is still the right way to do it in VS2008. However, Zeeshan Hirani suggested to me that with EF4, there’s a better way – the new CreateObjectSet method.

This let’s me pass in the entity type and create a queryable set.

A simple version would be:

public List<TEntity> ReturnSomeObjects<TEntity>()

{ context.CreateObjectSet<TEntity>(); }

Easy peasie.

Now what if I want to provide a field for sorting. I could use functional programming to pass in and use a strongly typed property to sort on. Alternatively, I could pass in a string and append a Query Builder method to the object set.

context.CreateObjectSet<TEntity>().OrderBy(“it.” + sortproperty)

Sweet. Much easier than dealing with MetadataWorkspace.

Thanks for getting me to think a little harder on this, Zeeshan!

  Sign up for my newsletter so you don't miss my conference & Pluralsight course announcements!  

4 thoughts on “An Improved Entity Framework Tip for EF4 thanks to Zeeshan

  1. Julie,

    You rock on all sessions i saw on EF at DevConnections!!! I still managed to learn few things here and there from your presentation.

    You did not present at pdc?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.