I’m looking for a tool that will dynamically generate Linq to Entity queries from a given entity, a Query By Entity (Example), if you will. Given an entity and the object context it belongs to, the generator returns an ObectQuery or IQueryable that could be further modified or executed. Ideally, the query builder would not directly reference Entity Model, rather it would use the object context to build the query from the model. I imagine the code looking something like this:
QueryBuilder qb = new QueryBuilder(new EntitiesContext());
Customer c = new Customer();
qb.Add(c);
c.FirstName = "Jim";
var qry = qb.BuildQuery();
int total = qry.Count();
The underlying query would look something like this:
var query = from c in ctx.Customers
where c.FirstName == "Jim"
select c;
Does such a thing already exist somewhere? I can imagine coding something like this myself, but I would rather start using something that already exists.
I'm not exactly sure what your goals are, if you would post some more information on your context (an actual problem), but Dynamic Linq might help you constructing linq queries dynamically:
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
Wiebe
I don't really see the value in a QueryBuilder. If it's as simple as in your sample you could only use it to find exact matches. If you need more complex queries you'd probably be better of using Linq directly.
You know that you can chain your queries? That's probably not exactly what you are looking for but you could do
IQueryable<Customers> source=context.Customers;
if (...)
{
source = from c in source
where c.FirstName.StartsWith("Jim")
select c;
}
if (...)
{
source = from c in source
where contries.Contains(c.Country)
select c;
}
// ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With