c# - 如何实现通用 GetById() 其中 Id 可以是各种类型

标签 c# asp.net-mvc generics repository-pattern

我正在尝试实现一个通用的 GetById(T id) 方法,该方法将满足可能具有不同 ID 类型的类型。在我的示例中,我有一个实体,其 ID 类型为 int,其中一个 ID 类型为 string

但是,我一直收到错误,我不知道为什么:

“int”类型必须是引用类型,以便在方法 IEntity 的泛型类型中将其用作参数“TId”

实体接口(interface):

为了迎合我的域模型,它可以具有 intstring 类型的 Id。

public interface IEntity<TId> where TId : class
{
    TId Id { get; set; }
}

实体实现:

public class EntityOne : IEntity<int>
{
    public int Id { get; set; }

    // Other model properties...
}

public class EntityTwo : IEntity<string>
{
    public string Id { get; set; }

    // Other model properties...
}

通用存储库接口(interface):

public interface IRepository<TEntity, TId> where TEntity : class, IEntity<TId>
{
    TEntity GetById(TId id);
}

通用存储库实现:

public abstract class Repository<TEntity, TId> : IRepository<TEntity, TId>
    where TEntity : class, IEntity<TId>
    where TId : class
{
    // Context setup...

    public virtual TEntity GetById(TId id)
    {
        return context.Set<TEntity>().SingleOrDefault(x => x.Id == id);
    }
}

存储库实现:

 public class EntityOneRepository : Repository<EntityOne, int>
    {
        // Initialise...
    }

    public class EntityTwoRepository : Repository<EntityTwo, string>
    {
        // Initialise...
    }

最佳答案

您应该从您的Repository 类中删除对 TId 的约束

public abstract class Repository<TEntity, TId> : IRepository<TEntity, TId>
where TEntity : class, IEntity<TId>
{
    public virtual TEntity GetById(TId id)
    {
        return context.Set<TEntity>().Find(id);
    }
}

关于c# - 如何实现通用 GetById() 其中 Id 可以是各种类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35779723/

相关文章:

java - Varargs 污染了堆

java - java中指定一个对象方法作为参数

c# - 使用 linq 合并 2 个具有重复键的字典

c# - Xamarin Android : System. IO.Compression.ZipFile.ExtractToDirectory 在 Release模式下失败

asp.net-mvc - MVC Controller 与开箱即用的 Sitecore Controller

c# - 以编程方式在 asp.net 应用程序的 microsoft.identityModel 中配置联合身份验证元素

.net - 用于 XML/JSON REST API 的 MVC2 或 WCF?

scala - 不同类型List的通用unapply方法

c# - 缺少 WCF 服务的 xml 注释的编译器警告

c# - 使用 ErrorProvider 和验证事件的表单验证