EF/LINQ:针对子类型的属性的Where()
我有一组 POCO,所有这些都实现了以下简单接口:
interface IIdObject
{
int Id { get; set; }
}
这些 POCO 的子集实现了这个附加接口:
interface IDeletableObject : IIdObject
{
bool IsDeleted { get; set; }
}
我有一个看起来像这样的存储库层次结构:
IRepository
; <:BasicRepository ; <:验证存储库 (其中 T 是 IIdObject)
我试图将 FilteringRepository 添加到层次结构中,以便所有实现 IDeletableObject
的 POCO 都有一个 Where(p => ; p.IsDeleted == false)
在任何其他查询发生之前应用过滤器。我的目标是避免仅为 IDeletableObjects 重复层次结构。
我的第一次尝试如下所示:
public override IQueryable<T> Query()
{
return base.Query().Where(t => ((IDeletableObject)t).IsDeleted == false);
}
这与 LINQ to Objects 配合良好,但是当我切换到 EF 后端时,我得到:“LINQ to Entities 仅支持转换实体数据模型原始类型。”
我继续尝试一些更奇特的参数化解决方案,但它们最终失败了,因为由于某种我不太明白的原因,我无法在以下情况下使 T 协变:
interface IQueryFilter<out T> // error
{
Expression<Func<T, bool>> GetFilter();
}
我很乐意详细介绍我更复杂的解决方案,如果它会有帮助,但我想我现在就停在这里,希望有人能给我一个尝试的想法。
预先非常感谢!
I have a set of POCOs, all of which implement the following simple interface:
interface IIdObject
{
int Id { get; set; }
}
A subset of these POCOs implement this additional interface:
interface IDeletableObject : IIdObject
{
bool IsDeleted { get; set; }
}
I have a repository hierarchy that looks something like this:
IRepository<T> <: BasicRepository<T> <: ValidatingRepository<T> (where T is IIdObject)
I'm trying to add a FilteringRepository to the hierarchy such that all of the POCOs that implement IDeletableObject
have a Where(p => p.IsDeleted == false)
filter applied before any other queries take place. My goal is to avoid duplicating the hierarchy solely for IDeletableObjects.
My first attempt looked like this:
public override IQueryable<T> Query()
{
return base.Query().Where(t => ((IDeletableObject)t).IsDeleted == false);
}
This works well with LINQ to Objects, but when I switch to an EF backend I get: "LINQ to Entities only supports casting Entity Data Model primitive types."
I went on to try some fancier parameterized solutions, but they ultimately failed because I couldn't make T covariant in the following case for some reason I don't quite understand:
interface IQueryFilter<out T> // error
{
Expression<Func<T, bool>> GetFilter();
}
I'd be happy to go into more detail on my more complicated solutions if it would help, but I think I'll stop here for now in hope that someone might have an idea for me to try.
Thanks very much in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这对于注释来说太大了,所以...
您可以动态创建表达式。我创建了辅助方法:
然后您可以使用:
编辑
您还可以使用动态 Linq 库。它也使用表达式,但不会强迫您思考它是如何工作的,只需将简单的条件写为字符串即可。我不知道它如何处理布尔值。
This is too big for comment, so...
You can create expressions dynamically. I've created helper methods:
Then you can use:
EDIT
You can also use Dynamic Linq Library. It uses expressions too, but doesn't force you to think about how it all works, just write simple conditions as string. I don't know how it handles bool values.