使用实体框架核心构建动态查询 - 通过步骤"构建查询"

时间:2018-04-10 10:12:37

标签: c# linq lambda dbset

我试图创建一个类来执行动态过滤器,具体取决于我将发送给其过滤器的参数"方法,但我在构建查询时面临一些困难。

使用我的以下代码更容易解​​释,我只是尝试根据我在输入中收到的内容来应用一些过滤器:

public class PeopleManager : Controller
    {
        private readonly MyPeopleContext _context;
        public PeopleManager(PeopleContext context)
        {
            _context = context;
        }

        public IEnumerable<Person> filter (int? id, string name, int? age)
        {
            var peoplequery = _context.People;
            if(id!=null)
            {
               peoplequery = peoplequery .Where(p => p.Id.Equals(id));
            }

            if(name!="")
            {
               peoplequery = peoplequery .Where(p => p.Name.Contains(name));
            }

            if(age!=null)
            {
               peoplequery  = peoplequery .Where(p => p.Age.Equals(age));
            }

            return peoplequery;
        }
    }

显然,我的代码无效,根据我发现的这个问题:

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Data.Entity.DbSet'

我设法编辑了我的代码,如下所示:

public IEnumerable<Person> filter (int? id, string name, int? age)
            {
                var people = _context.People;

                var peoplequery = from p in people select people;

                if(id!=null)
                {
                   peoplequery = peoplequery .Where(p => p.Id.Equals(id));
                }

                if(name!="")
                {
                   peoplequery = peoplequery .Where(p => p.Name.Contains(name));
                }

                if(age!=null)
                {
                   peoplequery  = peoplequery .Where(p => p.Age.Equals(age));
                }

                return peoplequery;
            }

但是这样做,我无法在我的lambda表达式中访问人物的属性,如id,name等...

如何在没有任何错误的情况下构建此条件查询?

1 个答案:

答案 0 :(得分:0)

我想你想像这样:

public class PeopleController : Controller
{
    private readonly MyPeopleContext _context;

    public PeopleManager(PeopleContext context)
    {
        _context = context;
    }

    public IEnumerable<Person> Filter (int? id, string name, int? age)
    {
        var peoplequery = _context.People.AsQueryable();
        if(id.HasValue)
        {
           peoplequery = peoplequery.Where(p => p.Id == id.Value);
        }
        if(!string.IsNullOrEmpty(name))
        {
           peoplequery = peoplequery.Where(p => p.Name.Contains(name));
        }
        if(age.HasValue)
        {
           peoplequery = peoplequery.Where(p => p.Age == age.Value);
        }

        return peoplequery.ToArray();
    }
}