Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query By Entity (Example)

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.

like image 569
TGnat Avatar asked Aug 30 '26 03:08

TGnat


2 Answers

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

like image 198
Wiebe Tijsma Avatar answered Sep 01 '26 16:09

Wiebe Tijsma


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;
}

// ...
like image 40
laktak Avatar answered Sep 01 '26 17:09

laktak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!