c# - 创建通用扩展方法时出现问题

标签 c# generics

现在我正在尝试创建一个通用方法来在我的存储库中包含外键。

我目前得到的是这个:

public static class ExtensionMethods
{
    private static IQueryable<T> IncludeProperties<T>(this DbSet<T> set, params Expression<Func<T, object>>[] includeProperties)
    {
        IQueryable<T> queryable = set;
        foreach (var includeProperty in includeProperties)
        {
            queryable = queryable.Include(includeProperty);
        }

        return queryable;
    }
}

但是在编译时出现错误:

The type 'T' must be a reference type in order to use it as parameter 'TEntity' in the generic type or method 'System.Data.Entity.DbSet'

这可能是什么问题?

最佳答案

追加where T : class到方法签名的末尾:

private static IQueryable<T> IncludeProperties<T>(
    this DbSet<T> set,
    params Expression<Func<T, object>>[] includeProperties)
    where T : class // <== add this constraint.
{
    ...
}

DbSet<TEntity>有这个限制,所以为了你的 TTEntity 兼容的类型参数,它必须具有相同的约束。

关于c# - 创建通用扩展方法时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26307700/

相关文章:

c# - 当 T 未知时,如何使用反射执行 List<object>.Cast<T>

java - 强制 Java 方法返回类型以适应特定的通用签名

c# - 使用 C# 泛型的助手

c# - 是否可以通过编程方式检查 selenium Remote Webdriver Server 是否正在运行

c# - 使用 C# .NET Core 3.1 返回具有属性的组成员的 Active Directory

c# - 持久计算列上的 "A dependent property in a ReferentialConstraint is mapped to a store-generated column."(首先是 EntityFramework 数据库)

java - 为什么这个通用代码可以编译?

c# - 捕获并解决实体验证错误

c# - 告诉 RavenDB 忽略一个属性

c# - 带有运算符的泛型 C#