Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 4 LINQ to Entities Queries Over WCF

I need to create a WCF service to return objects queried from a database through Entity Framework. Most articles I've read suggests that I should create a method for each type of query. But I think this will cause an explosion in the number of methods I will create, for example:

  • GetAllCars()
  • GetCarsByBrand(string brandName)
  • GetCarsByYear(int year)
  • GetCarsByBrandAndYear(string brandName, int year)
  • GetCarsByTireSize(float tireSize)
  • GetCarsByEngineType(string engineType)
  • GetCarsByEngineSizeAndType(float engineSize, string engineType)
  • GetCarsByEngineSizeBetween(float lowerEngineSize, float upperEngineSize)
  • etc..

On top of that, if a new query is required, then I will have to create a new method to supoport it.

There must be a better more generic way to do this. What would be ideal is if the client can create an expression tree via LINQ, send it over WCF, then run the query through entity framework. Then I can have one method to support all queries. For example:

  • QueryCars(Expression expression)

Or send an expression as a string:

  • QueryCars(string expression)

How have developers solved this problem of flexible querying?

I am currently working in .NET 4.0. Security is not really a concern since this is just an internal app.

like image 435
Mas Avatar asked Nov 19 '25 22:11

Mas


1 Answers

What you're looking for is WCF Data Services. It uses the OData protocol to query the data with Linq.

Example with the Stack Overflow OData service:

var query = from u in service.Users
            orderby u.Reputation descending
            select u;

Console.WriteLine ("Top ten Stack Overflow users");
foreach (var u in query.Take(10))
{
    Console.WriteLine ("{0}: {1}", u.DisplayName, u.Reputation);
}

In the code above, service.Users is of type IQueryable<User>, which allows you to query it with an expression tree.

You can easily try the SO service with LINQPad, or by adding a reference to the service URL in a VS project.

like image 140
Thomas Levesque Avatar answered Nov 22 '25 02:11

Thomas Levesque