Passing a WHERE clause for a Linq-to-Sql query as a parameter

前端 未结 2 476
太阳男子
太阳男子 2021-01-28 01:05

This is probably pushing the boundaries of Linq-to-Sql a bit but given how versatile it has been so far I thought I\'d ask.

I have 3 queries that are selecting identical

2条回答
  •  不要未来只要你来
    2021-01-28 02:04

    What you can do is passing an object that allows filtering an IQueryable. When you do this you can write code like this is your service layer:

    public Person[] GetAllPersons(IEntityFilter filter)
    {
        IQueryable query = this.db.Persons;
    
        query = filter.Filter(query);
    
        return query.ToArray();
    }
    

    and in your calling layer, you can define a filter like this:

    IEntityFilter filter =
        from person in EntityFilter.AsQueryable()
        where person.Name.StartsWith("a")
        where person.Id < 100
        select person;
    
    // or (same result, but without LINQyness)
    IEntityFilter filter = EntityFilter
        .Where(p => p.Name.StartsWith("a"))
        .Where(p => p.Id < 100);
    
    // Call the BL with the filter.
    var persons = BusinessLayer.GetAllPersons(filter);
    

    You can find the source code of an implementation of this EntityFilter here (it's around 40 lines of code) and as blog post about it here.

    Please note that your query is a bit more complex than the example I've shown here, so it could take a bit more work to define the correct filter.

提交回复
热议问题