Возвращение пустого IQueryable <>

У меня есть этот метод, который пытается получить список вещей:

 private static IQueryable<Thing> GetThings(int thingsType)
        {
                try
                {
                    return from thing in entities.thing.Include("thingStuff")
                           select thing;
                }
                catch (Exception exception)
                {
                    return new EnumerableQuery<Thing>(?????);
                }
            }

        }

Я хочу вернуть пустой IQueryable, если я не могу по какой-либо причине получить запрос для запуска. Я не хочу возвращать NULL, потому что это может нарушить код вызова. Возможно ли, или я полностью ошибаюсь?

Ответы

Ответ 1

Эти ответы хороши и работают, однако я всегда чувствовал, что использует Empty и не создаю новый List is clean:

Enumerable.Empty<Thing>().AsQueryable();

Ответ 2

Попробуйте следующее:

private static IQueryable<Thing> GetThings(int thingsType)
    {
            IQueryable<Thing> things = new List<Thing>().AsQueryable();
            try
            {
                things = from thing in entities.thing.Include("thingStuff")
                       select thing;

                return things;
            }
            catch (Exception exception)
            {
                return things;
            }
        }

Ответ 3

Я бы добавил блок finally {} и поместил мой возвращаемый тип в этот код.

Это позаботится об этом, вернув тип, который ожидает ваше приложение.

private static IQueryable<T> GetThings(int thingsType)
    {
            IQueryable<T> list = new List<Thing>().AsQueryable();
            try
            {
                list = from thing in entities.thing.Include("thingStuff")
                       select t;
            }
            catch (Exception exception)
            {
               // handle exception here;
            }
            finally {    
              return list;
            }

        }

    }

Ответ 4

Я думаю, что это будет более аккуратно:

private static IQueryable<T> GetThings(int thingsType)
{
    try
    {
        return from thing in entities.thing.Include("thingStuff")
                   select t;
    }
    catch (Exception exception)
    {
       // Exception handling code goes here

       return new List<Thing>().AsQueryable();
    }
}

Ответ 5

Возврат пустой IQueryable < > DbSet.Take(0)