gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:24:22 25 4
gpt4 key购买 nike

我正在尝试实现一个通用的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com