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

前端 未结 2 446
太阳男子
太阳男子 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 01:46

    Yes it is.

    var times = DataContext.EventDateTimes;
    if (cond)
        times = times.Where(time => time.StartDate <= ...);
    
    from row in ... join time in times ...
    
    0 讨论(0)
  • 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<Person> filter)
    {
        IQueryable<Person> query = this.db.Persons;
    
        query = filter.Filter(query);
    
        return query.ToArray();
    }
    

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

    IEntityFilter<Person> filter =
        from person in EntityFilter<Person>.AsQueryable()
        where person.Name.StartsWith("a")
        where person.Id < 100
        select person;
    
    // or (same result, but without LINQyness)
    IEntityFilter<Person> filter = EntityFilter<Person>
        .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<T> 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.

    0 讨论(0)
提交回复
热议问题