【发布时间】:2016-10-07 08:56:17
【问题描述】:
public interface ICardEntity { ... }
public class Card : ICardEntity { ... }
public static class MyExtensions
{
public static List<T> ToList<T>(this IQueryable<T> query) where T : ICardEntity
{ ... }
}
// DbContext
public class ApplicationDbContext : DbContext
{
public DbSet<Card> Cards { get; set; }
}
.....
var list = dbContext.Cards
.ToList(); // -- OK, my extension is called
var list2 = dbContext.Cards
.GroupBy(t => new { Type = t.Type})
.ToList(); // -- Compile error. Why not System.Linq.Enumerable.ToList() is called?
我希望我的 ToList 只为 IQueryable
错误信息:
类型'System.Linq.IGrouping, Nucleo.Tests.Models.Card>' 不能用作类型参数 'T' 泛型类型或方法“MyExtensions.ToList(IQueryable)”。那里 不是从隐式引用转换 'System.Linq.IGrouping' 到 'ICardEntity'。
【问题讨论】:
-
泛型类型约束不参与重载决议。
-
顺便说一句,不需要创建匿名类型:
GroupBy(t => new { Type = t.Type })。为什么不GroupBy(t => t.Type)?
标签: c# entity-framework linq generics