具有相关数据的多个条件

时间:2012-12-03 19:26:00

标签: entity-framework

我有一种情况需要对查询应用一些过滤器,所以我有一个代表过滤器的类:

public class ReportNoteFilterDto
{
    public int Year { get; set; }
    public int Month { get; set; }
}

我需要根据此过滤器选择数据。

var query = _db.User;

if (filter.Month > 0 && filter.Month <= 12)
    query.Select(u => new {
        User = u,
        Notes = u.Notes.Where(n => n.Begin.Month == filter.Month)
    });

if (filter.Year > 2011)
    query.Select(u => new
    {
        User = u,
        Notes = u.Notes.Where(n => n.Begin.Year == filter.Year)
    });

var results = query.Include("Notes.Foo.Bar").ToList(); //doesn't work

我也需要选择Notes.Foo.Bar。

如何进行多重过滤?

1 个答案:

答案 0 :(得分:1)

您没有将第一个查询的结果分配给 query 变量

您可以在此处看到类似问题是如何解决的:

class Program
{
    //A simple class to hold the results
    public class Result
    {
        public string Item { get; set; }

        public IQueryable<string> Collection { get; set; }
    }

    static void Main(string[] args)
    {
        var list1 = new List<Result>();
        var objects = list1.Select(o => new Result { Item = o.Item, Collection = o.Collection.Where(a=> a.Length == 10) });
        if(true)
           objects = objects.Select(o => new Result { Item = o.Item, Collection = o.Collection.Where(a=> a.Length > 15) });
    }
}