返回的通用输入类型与LINQ类型约束实体(EF4.1) [英] Return input type of generic with type constraint in LINQ to Entities (EF4.1)

查看:88
本文介绍了返回的通用输入类型与LINQ类型约束实体(EF4.1)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有被过滤标签一个LINQ的IQueryable一个简单的扩展方法。我使用这个与LINQ到实体具有的接口:

I have a simple extension method for filtering a LINQ IQueryable by tags. I'm using this with LINQ to Entities with an interface of:

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实体转换异常:

This leads to a LINQ to Entities cast exception:

无法转换类型'ReleaseGateway.Models.Product键入
'ReleaseGateway.Models.ITaggable'。LINQ到实体仅支持
铸造实体数据模型基本类型。
(System.NotSupportedException)一个System.NotSupportedException为
抓住了:无法投类型'Project.Models.Product键入
'Project.Models.ITaggableLINQ到实体只支持铸造
实体数据模型的基本类型。

"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在我的应用程序代码:

It works without the constraint like this, but I have to explicitly declare the type T in my application code:

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>();
}



问:为什么类型约束铸返回类型?我能改写这个拿推断从扩展方法调用者的类型的优势在哪里?

Question: Why does the type constraint cast the return type? Can I rewrite this to take advantage of inferring the type from the extension method caller?

推荐答案

我一直在寻找相同的答案,没有满意提供的答案的语法清洁度,我一直在寻找,发现这个帖子。

I was looking for the same answer and not being satisfied with the syntactic cleanliness of the answers provided, I kept looking and found this post.

TL;博士; - 添加类的约束和它的作品

tl;dr; - add class to your constraints and it works.

LINQ到实体仅支持铸造EDM原始或枚举类型的IEntity接口

public static IQueryable<T> WhereTagged<T>(this IQueryable<T> set, string tag)
    where T: class, ITaggable

这篇关于返回的通用输入类型与LINQ类型约束实体(EF4.1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆