【问题标题】:Extension Method For IQueryable not workingIQueryable 的扩展方法不起作用
【发布时间】:2014-12-06 11:21:03
【问题描述】:

我写了一个扩展方法:

public static IQueryable<TSource> ConditionalDefaultEmpty<TSource>(this IQueryable<TSource> source, bool condition)
{
    return condition ? source.DefaultIfEmpty() : source ;
}

然后我调用了这个方法,像这样:

var q = from sr in myDb.tblStudentsRegInfos
        from de in myDb.tblDisciplinesEvents.Where(e => sr.Serial == e.tblStudentsRegInfoRef 
                                                     && e.tblStudentsRegInfoRef == studentRegId 
                                                     && (!forStudent || e.PublishOnInternet)
                                                     && (!formDate.HasValue || e.RegDate >= formDate) 
                                                     && (!toDate.HasValue || e.RegDate <= toDate))
                    .ConditionalDefaultEmpty(noPrintAll)
        join dt in myDb.tblDisciplinesTitles on de.tblDisciplinesTitlesRef equals dt.Serial
        where sr.Serial == studentRegId
        group sr by new
                {
...
                }
                into std
                select new
                {....
                };

但我收到此错误:

会员访问[列名]不合法......

我该如何解决这个问题?

更新:我了解到 EF 无法编译为 IQueryable...

【问题讨论】:

  • 不使用你的方法时查询是否有效?
  • 是的,它的工作非常好。
  • 您能否将第二个 from(使用您的方法的部分)作为单独的查询执行?
  • 很遗憾没有,或者我不这么认为
  • 我的意思是,它会崩溃还是您无法测试它?

标签: c# linq entity-framework iqueryable


【解决方案1】:

您只是不能添加您的自定义扩展方法,并希望实体框架能够将其转换为 SQL,尽管这样会很酷,至少对于此类情况而言。

也就是说,你可以把IQueryable变成IEnumerable

.AsEnumerable()
.ConditionalDefaultEmpty(noPrintAll)

【讨论】:

  • 我不理解反对票,因为这正是原因。可能是因为子查询中的AsEnumerable() 无济于事,因为 EF 将无法仅将查询的第一部分转换为 SQL 并在内存中完成其余部分。
猜你喜欢
  • 1970-01-01
  • 2012-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多