gpt4 book ai didi

c# - 根据方法参数构建 IQueryable

转载 作者:太空宇宙 更新时间:2023-11-03 13:44:55 25 4
gpt4 key购买 nike

我有一个类似于下面的 API 方法。

是否可以附加 IQueryable 以便最终查询具有执行 where 语句的项目列表,或者我应该使用 SqlQuery 属性并构建原始 SQL 字符串。

    public IEnumerable<Message> GetMessagesFromApi(DateTime? dateFrom = null, DateTime? dateTo = null, int flag = -1, int messageType = 1, bool media =false)
{
if (dateFrom == null)
dateFrom = DateTime.MinValue;

if (dateTo == null)
dateTo = DateTime.MaxValue;

IQueryable<Message> query = null;


query = db.Messages.Where(x => x.Created >= dateFrom && x.Created <= dateTo);


if (flag >= 0)
{
//Append the where statement on dates to now include Flag
query = query.Where(x => x.Flag == flag);
}

//Here it should execute against Where date >= and date <= and flag = 1
}

最佳答案

Is it possible to append the IQueryable so the final query has a list of items to execute a where statement.

是的。您的代码应该可以正常工作。如果你想构建一个 IEnumerable<Message>,你只需要执行这个对于结果。

//Here it should execute against Where date >= and date <= and flag = 1
return query.ToList();

请注意,您可以使用 AsEnumerable()甚至只是返回 query直接(因为 IQueryable<T> 实现了 IEnumerable<T> ),但如果用户多次枚举您的结果,这将导致问题,因为每次枚举都会命中数据库。

我个人会这样写:

public IEnumerable<Message> GetMessagesFromApi(DateTime? dateFrom = null, DateTime? dateTo = null, int flag = -1, int messageType = 1, bool media =false)
{
IQueryable<Message> query = db.Messages;

if(dateFrom.HasValue)
query = query.Where(x => x.Created >= dateFrom);
if(dateTo.HasValue)
query = query.Where(x => x.Created <= dateTo);
if(flag >= 0)
query = query.Where(x => x.Flag == flag);
// others as needed, such as media...

return query.ToList();
}

关于c# - 根据方法参数构建 IQueryable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15686793/

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