返回空IQueryable <>

Otá*_*cio 20 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>(?????);
                }
            }

        }
Run Code Online (Sandbox Code Playgroud)

如果我不能以任何理由让查询运行,我想返回一个空的IQueryable.我不想返回NULL,因为这可能会破坏调用代码.是否可能或者我对此完全错了?

小智 50

这些答案很好并且可以正常工作,但是我总是觉得使用Empty而不是创建一个新的List更清洁:

Enumerable.Empty<Thing>().AsQueryable();
Run Code Online (Sandbox Code Playgroud)

  • 但请注意,如果您在EF6中使用await/async,最终会出现以下异常:https://msdn.microsoft.com/en-us/data/dn313107.aspx - 请检查此链接是否存在异步方式 - http:// stackoverflow.com/questions/33305495/how-to-return-empty-iqueryable-in-an-async-repository-method (5认同)
  • 对我来说,这个解决方案不适用于复杂的查询。EF Core 抛出“InvalidOperationException”,并显示消息““NavigationExpandingExpressionVisitor”处理 LINQ 表达式 XXX 失败”。这可能表明 EF Core` 中存在错误或限制。我刚刚使用了 .Where(x =&gt; false)` ,它有效。 (3认同)

mre*_*ros 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;
            }
        }
Run Code Online (Sandbox Code Playgroud)


EL *_*bov 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;
            }

        }

    }
Run Code Online (Sandbox Code Playgroud)

  • 绝对同意,异常应该以某种方式处理,然后返回空列表的调用应该在finally块中返回. (2认同)