我是 REST api 的新手,我想知道创建一个 CRUD 存储库的最佳方法是什么,该存储库处理具有不同类型的 ID/主键的实体:带有 int 的汽车、带有字符串的人和包含的地址两个不同的字符串(地址和邮政编码)。我创建了一个 IRepository
public interface IRepository<EntityBase>
{
Task<PayoutResult> Insert(EntityBase entity);
bool EntityExists(EntityBase entity);
}
并使所有模型都实现了 EntityBase,但我不确定当它们都具有三种不同的 ID 类型时 BaseEntity 应该是什么样子?
最佳答案
我会推荐这样的接口(interface)IEntity
:
public interface IEntity<TKey> where TKey : IEquatable<TKey>
{
TKey Id { get; set; }
}
所有实体都应该实现这个接口(interface),然后你就可以像这样拥有IRepository
:
public interface IRepository<TEntity, in TKey> where TEntity : IEntity<TKey> where TKey : IEquatable<TKey>
{
(...)
Task<TEntity> GetByIdAsync(TKey id);
void Insert(TEntity entity);
(...)
}
关于c# - 当实体的 id 是不同类型(string/int)时,如何创建 CRUD 存储库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55103756/