LINQ 到实体转换问题
我正在尝试以通用方式过滤 LINQ-to-entities 查询,但我不断收到错误。这是一段代码:
private IQueryable<T> FilterDeletedEntities<T>(IQueryable<T> entities)
{
if (typeof(IDeletable).IsAssignableFrom(typeof(T)))
{
var deletableEntities = (IQueryable<IDeletable>)entities;
deletableEntities = deletableEntities.Where(entity => !entity.Deleted);
entities = (IQueryable<T>)deletableEntities;
}
return entities;
}
基本上,我试图过滤掉已删除的实体(即“已删除”字段为“true”),当且仅当该实体是 IDeletable(即它具有“已删除”字段)时。问题是我无法强制转换 IQueryable<可删除>返回 IQueryable< T>。
关于如何解决这个问题有什么想法吗?在你问之前:是的,这个方法必须是通用的。
提前致谢!
I'm trying to filter a LINQ-to-entities query in a generic way, but I keep getting an error. Here is a piece of code:
private IQueryable<T> FilterDeletedEntities<T>(IQueryable<T> entities)
{
if (typeof(IDeletable).IsAssignableFrom(typeof(T)))
{
var deletableEntities = (IQueryable<IDeletable>)entities;
deletableEntities = deletableEntities.Where(entity => !entity.Deleted);
entities = (IQueryable<T>)deletableEntities;
}
return entities;
}
Basically I'm trying to filter out deleted entities (i.e. 'Deleted' field is 'true'), if and only if the entity is IDeletable (i.e. it has the 'Deleted' field). The problem is that I can't cast IQueryable< IDeletable > back to IQueryable< T >.
Any ideas on how to fix this? And before you ask: yes, this method has to be generic.
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
但您可以使用
Cast()
来转换它。您也可以使用它来区分 IDeletable,例如,
But you can use
Cast<T>()
to convert it.You could also use it to case to IDeletable as well, for example,
我能够通过这样做解决我的问题:
感谢 tvanfosson 的灵感。
I was able to solve my problem by doing this:
Thanks to tvanfosson for the inspiration.
如果您可以假设没有人需要使用未实现 IDeletable 的 T 调用此方法,则可以限制 T:
作为奖励,您不需要强制转换任何内容或使用反射来测试 IDeletable。
If you can assume that no one will need to call this method with T that does not implement IDeletable, you can restrict T:
As a bonus, you won't need to cast anything or use reflection to test for IDeletable.