返回空IQueryable<>

时间:2012-12-13 20:19:34

标签: entity-framework

我有这种方法试图得到一些东西:

 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,因为这可能会破坏调用代码。是否可能或者我对此完全错了?

5 个答案:

答案 0 :(得分:44)

这些答案很好并且有效,但是我一直觉得使用Empty而不是创建一个新的List更清洁:

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

答案 1 :(得分:9)

尝试以下方法:

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

答案 2 :(得分:5)

我会添加块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;
            }

        }

    }

答案 3 :(得分:1)

我认为这会更整洁:

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

答案 4 :(得分:1)

  

返回空IQueryable&lt;&gt;   DbSet.Take(0)

相关问题