根据方法参数构建IQueryable

时间:2013-03-28 16:11:03

标签: c# .net entity-framework generics iqueryable

我有一个类似于下面的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
    }

1 个答案:

答案 0 :(得分:1)

  

是否可以附加IQueryable,以便最终查询具有执行where语句的项列表。

是。你的代码应该工作正常。如果要为结果构建IEnumerable<Message>,则只需执行此操作即可。

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

请注意,您可以使用AsEnumerable()甚至直接返回query(因为IQueryable<T>实施IEnumerable<T>),但如果用户更多地枚举您的结果,这会导致问题而不是一次,因为每个枚举都会击中DB。

我个人会把它写成:

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