开发者

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开发者_如何学JAVA 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.


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.


By your describtion you don't need pure WCF services but WCF Data Services instead. Data service allow you exposing IQueryable and define the Linq query on the client.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜