views:

115

answers:

1

Basically I'd be looking to implement a method like this.

IQueryAble GetQuery<T>(Entities db) or extension method Entities.GetQuery<T>()

This way you could do things like this

public IQueryable<T> GetAll()
{
return yourEntityClasses.GetQuery<T>();
}

which would return a SELECT * FROM query expression and obviously from there you could make addtional generic methods for sorting, pagination, where expressions, etc on top of this would save you from having to repeat the code for these methods for each table. I know SubSonic3 does a very good job of this, but was trying to duplicate some of the functionality in an EntityFramework project I am working on. Only thing I see in EF is CreateQuery and ObjectQuery but both of those require you to pass a querystring in which would require you to know the table name.

+2  A: 

Well it is possible to get the string that you need to put into the CreateQuery method automatically.

Basically it is just string.Format("[{0}]",entitySetName);

How do you get the entity set name, assuming you have don't use something called MEST, most people don't, you can use some a functions I wrote in this Tip to get the EntitySet for T and from that the name.

Once you do that it should be pretty trivial for you to write the Extension Method

i.e.

public static IQueryable<T> GetAll<T>(this ObjectContext context)
{
    var wkspace = context.MetadataWorkspace;
    EntitySet set = wkspace
       .GetEntitySets(wkspace.GetCSpaceEntityType<T>())
       .Single(); 
    return context.CreateQuery<T>(string.Format("[{0}]",set.Name);
}

See the above tip for the other functions used.

Hope this helps

Alex

Alex James
Thanks, Alex. I would have used typeof(T).Name, and maybe not found out why not for a little while.
John Saunders
John, cool, I'm happy I could help
Alex James
Yep this works - thanks
Jeremy Coenen