我已经用EF4设置了这个项目,我正在使用LINQ to Entities来形成查询。
我在查询时遇到了一些问题,该查询涉及许多条件where子句和几个左外部连接。
我已经用下面的扩展方法部分解决了条件where子句(我发现了here)。
public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, bool condition, Expression<Func<TSource, bool>> predicate)
{
if (condition)
return source.Where(predicate);
else
return source;
}我现在的问题是,当我在连接表上使用扩展方法时,LINQ to Entities不能识别它。
以下是查询的一部分:
from p in context.Entities.OfType<Patient>()
.WhereIf(!string.IsNullOrEmpty(name), p => p.Name.Contains(name))
from c in context.Contacts
.Where(cp => cp.EntityID == p.EntityId).DefaultIfEmpty()
.WhereIf(timestamp != null, c => c.Timestamp > timestamp)我之所以说部分解决,是因为它在这个查询中第一次(患者姓名)工作得很好,但是第二次(时间戳)它给出了这个错误:
LINQ to Entities does not recognize the method 'System.Linq.IQueryable`1[x.Contact] WhereIf[Contact](System.Linq.IQueryable`1[x.Contact], Boolean, System.Linq.Expressions.Expression`1[System.Func`2[x.Contact,System.Boolean]])' method, and this method cannot be translated into a store expression.所以,我想知道有没有人知道我怎么解决这个问题?
发布于 2011-05-30 16:10:22
问题是EF无法识别SelectMany中的WhereIf。将查询重写为方法语法会产生如下结果(查询不完整):
context.Entities.OfType<Patient>()
.WhereIf(!string.IsNullOrEmpty(name), p => p.Name.Contains(name))
.SelectMany(
p => context.Contacts
.Where(cp => cp.EntityID == p.EntityId).DefaultIfEmpty()
.WhereIf(timestamp != null, c => c.Timestamp > timestamp),
(p, c) => new { p, c }
)问题出在最后一个WhereIf。您应该能够将其移动到SelectMany之外
context.Entities.OfType<Patient>()
.WhereIf(!string.IsNullOrEmpty(name), p => p.Name.Contains(name))
.SelectMany(
p => context.Contacts
.Where(cp => cp.EntityID == p.EntityId).DefaultIfEmpty(),
(p, c) => new { p, c }
)
.WhereIf(timestamp != null, x => x.c.Timestamp > timestamp)您可以通过将查询转换为ObjectQuery并调用ToTraceString方法来检查生成的SQL,看看是否得到了您真正想要的结果
var query = context.Entities.OfType<Patient>() ...
Console.WriteLine(((ObjectQuery) query).ToTraceString());发布于 2011-05-30 15:21:08
为什么不使用Where(timestamp == null || c.Timestamp > timestamp)?
https://stackoverflow.com/questions/6173031
复制相似问题