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.

E.g.

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!

#1 Daniel Wertheim on 11.13.2009 at 6:01 PM

Hi!

I have been writing some posts about this at my blog this week. I also cover how you can autoregister mappings etc. The topic is code-only. The latest post can be found here: daniel.wertheim.se/.../entity-framewor

//Daniel

#2 Muhammad Mosa on 11.15.2009 at 9:00 AM

Cool tip, just shoutitout.

Thanks to Zeeshan and to you Julie.

In fact Zeeshan did a great work on hist free eBook he made for EF v1 last year.

Nice tip

#3 Zeeshan Hirani on 11.17.2009 at 6:01 PM

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?

#4 Julie on 11.17.2009 at 6:16 PM

Thanks!

I'm sure I could learn a thing or two hundred about EF from you too! :)

I'll be presenting at www.notatpdc.com tomorrow. :)

Leave a Comment