我有一个简单的扩展方法,用于通过标签过滤LINQ IQueryable.我正在使用LINQ to Entities与以下界面:
public interface ITaggable { ICollection<Tag> Tags { get; } }
以下内容不起作用,返回IQueryable< ITaggable>而不是IQueryable< T:
public static IQueryable<T> WhereTagged<T>(this IQueryable<T> set,string tag) where T:ITaggable { return set.Where(s=>s.Tags.Any(t=>t.Name.ToLower() == tag.ToLower())); }
这导致LINQ to Entities投放异常:
“Unable to cast the type ‘ReleaseGateway.Models.Product’ to type
‘ReleaseGateway.Models.ITaggable’. LINQ to Entities only supports
casting Entity Data Model primitive types.”
(System.NotSupportedException) A System.NotSupportedException was
caught: “Unable to cast the type ‘Project.Models.Product’ to type
‘Project.Models.ITaggable’. LINQ to Entities only supports casting
Entity Data Model primitive types.”
它没有这样的约束,但我必须在应用程序代码中显式声明类型T:
public static IQueryable<T> WhereTagged<T>(this IQueryable<ITaggable> set,string tag) { return set.Where(s=>s.Tags.Any(t=>t.Name.ToLower() == tag.ToLower())).Cast<T>(); }
解决方法
我正在寻找同样的答案,不满足于提供的答案的句法清洁度,我一直在寻找并发现这篇文章.
TL;博士; – 添加类的约束,它的工作原理.
LINQ to Entities only supports casting EDM primitive or enumeration types with IEntity interface
public static IQueryable<T> WhereTagged<T>(this IQueryable<T> set,string tag) where T: class,ITaggable