我会让代码自己说话:
public interface ISoftDeletable {
bool IsDeleted {get; set;}
}
public static class Extensions {
public IQueryable<T> Active<T>(this IQueryable<T> q) where T : ISoftDeletable {
return q.Where(t => !t.IsDeleted);
}
}
public partial class Thing : ISoftDeletable {
...
}
...
var query = from tc in db.ThingContainers
where tc.Things.Active().Any(t => t.SatisfiesOtherCondition)
select new { ... }; // throws System.NotSupportedException
错误是:
LINQ to Entities 无法识别方法 'System.Collections.Generic.IQueryable`1[Thing] ActiveThing' 方法,并且此方法无法转换为存储表达式。
你明白了:我想要一种流利的表达方式,这样ISoftDeletable
我就可以用一段简单的、可重用的代码添加一个“where”子句。此处的示例不起作用,因为 Linq2Entities 不知道如何处理我的Active()
方法。
我在这里给出的例子很简单,但在我的真实代码中,Active()
扩展包含一组更复杂的条件,我不想在我的代码中复制和粘贴。
有什么建议么?