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!
Sign up for my newsletter so you don't miss my conference & Pluralsight course announcements!
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
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
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?
Thanks!
I’m sure I could learn a thing or two hundred about EF from you too! 🙂
I’ll be presenting at http://www.notatpdc.com tomorrow. 🙂