gpt4 book ai didi

c# - 使用 Entity Framework 核心构建动态查询 - 构建查询 "by steps"

转载 作者:行者123 更新时间:2023-11-30 18:14:45 25 4
gpt4 key购买 nike

我正在尝试创建一个类来执行动态过滤器,这取决于我将发送给它的“过滤器”方法的参数,但我在构建查询时遇到了一些困难。

用下面的代码更容易解​​释,我只是尝试根据输入的内容应用一些过滤器:

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 等。

我怎样才能不出错地构建这个条件查询?

最佳答案

我猜你想拥有这样的东西:

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

关于c# - 使用 Entity Framework 核心构建动态查询 - 构建查询 "by steps",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49750998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com