代码之家  ›  专栏  ›  技术社区  ›  Mantorok

将LINQ to SQL查询的WHERE子句作为参数传递

  •  0
  • Mantorok  · 技术社区  · 16 年前

    这可能有点超出了linq-to-sql的界限,但是考虑到目前为止它的多功能性,我想我会问。

    我有3个选择相同信息的查询,它们只在 哪里 子句,现在我知道可以传入委托,但这只允许我过滤已经返回的结果,但我希望通过参数构建查询以确保效率。

    以下是查询:

    from row in DataContext.PublishedEvents
    join link in DataContext.PublishedEvent_EventDateTimes
        on row.guid equals link.container
    join time in DataContext.EventDateTimes on link.item equals time.guid
    where row.ApprovalStatus == "Approved"
        && row.EventType == "Event"
        && time.StartDate <= DateTime.Now.Date.AddDays(1)
        && (!time.EndDate.HasValue || time.EndDate.Value >= DateTime.Now.Date.AddDays(1))
    orderby time.StartDate
    select new EventDetails
    {
        Title = row.EventName,
        Description = TrimDescription(row.Description)
    };
    

    我想通过参数应用的代码是:

    time.StartDate <= DateTime.Now.Date.AddDays(1) &&
    (!time.EndDate.HasValue || time.EndDate.Value >= DateTime.Now.Date.AddDays(1))
    

    这有可能吗?我不这么认为,但我想我先退房。

    谢谢

    2 回复  |  直到 16 年前
        1
  •  2
  •   Marcelo Cantos    16 年前

    是的。

    var times = DataContext.EventDateTimes;
    if (cond)
        times = times.Where(time => time.StartDate <= ...);
    
    from row in ... join time in times ...
    
        2
  •  2
  •   Steven    12 年前

    您可以做的是传递一个对象,该对象允许过滤一个iQuery。当您这样做时,您可以编写这样的代码:这是您的服务层:

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

    在调用层中,可以这样定义一个过滤器:

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

    您可以找到此的实现的源代码 EntityFilter<T> here (大约有40行代码)作为博客文章 here .

    请注意,您的查询比我在这里展示的示例要复杂一些,因此定义正确的过滤器可能需要更多的工作。