【问题标题】:Passing a WHERE clause for a Linq-to-Sql query as a parameter将 Linq-to-Sql 查询的 WHERE 子句作为参数传递
【发布时间】:2014-08-11 20:16:57
【问题描述】:

这可能稍微突破了 Linq-to-Sql 的界限,但考虑到它迄今为止的用途广泛,我想我会问。

我有 3 个查询选择相同的信息,并且仅在 where 子句中有所不同,现在我知道我可以传入一个委托,但这仅允许我过滤已经返回的结果,但我希望通过参数建立查询以确保效率。

这里是查询:

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

这可能吗?我不这么认为,但我想我会先检查一下。

谢谢

【问题讨论】:

    标签: c# linq-to-sql


    【解决方案1】:

    是的。

    var times = DataContext.EventDateTimes;
    if (cond)
        times = times.Where(time => time.StartDate <= ...);
    
    from row in ... join time in times ...
    

    【讨论】:

      【解决方案2】:

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

      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&lt;T&gt; here 的实现源代码(大约 40 行代码)以及关于它的博客文章 here

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-06
        • 1970-01-01
        • 2020-12-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多