将两个查询合并为一个查询

时间:2012-04-25 07:33:56

标签: c# sql asp.net-mvc-3 linq entity-framework-4

我有两个查询,它们都有效但需要将它们合并为一个有效的查询

查询1

  var now = DateTime.Now;
  var twoWeeksAgo = now.AddDays(-14);

  var advert =
      from m in db.tbl_Property
      where m.Prop_Update >= twoWeeksAgo && m.Prop_Update <= now
      select m;

查询2

  var Props = 
      from n in db.tbl_Property.
      Where(c => c.Prop_AvailableSpaces > 0)
      select n;

欢迎任何帮助或建议

4 个答案:

答案 0 :(得分:3)

我会将这些查询更改为传入原始IQueryable<Property>(或任何类型),然后您可以执行以下操作:

var advert = from m in source
             where m.Prop_Update >= twoWeeksAgo && m.Prop_Update <= now
             select m;

db.tbl_Property作为source传递,然后:

var Props = from n in filteredProperties
            where n.Prop_AvailableSpaces > 0
            select n;

即。组合物

答案 1 :(得分:2)

你的意思是:

var now = DateTime.Now;
var twoWeeksAgo = now.AddDays(-14);

var advert = db.tbl_Property
               .Where(m => m.Prop_Update >= twoWeeksAgo && m.Prop_Update <= now
                           && m.Prop_AvailableSpaces > 0);

或者也许与||结合代替:

var advert = db.tbl_Property
               .Where(m => (m.Prop_Update >= twoWeeksAgo && m.Prop_Update <= now)
                           || m.Prop_AvailableSpaces > 0);

(请注意,我没有在这里使用查询表达式,因为您只使用单个where子句 。)

答案 2 :(得分:0)

也许是这样的:

var advert =
            from m in db.tbl_Property
            where 
                (m.Prop_Update >= twoWeeksAgo && m.Prop_Update <= now)
                || (m.Prop_AvailableSpaces > 0)

            select m;

答案 3 :(得分:0)

     var advert = db.tbl_Property.Where(m => m.Prop_Update >= twoWeeksAgo 
     && m.Prop_Update <= now && m.Prop_AvailableSpaces > 0);