C# 当实体的ID是不同类型(string/int)时,如何创建CRUD存储库?
我对RESTAPI非常陌生,我想知道创建CRUD存储库的最佳方法是什么,该存储库可以处理具有不同类型ID/主键的实体:带有int的Car、带有字符串的Person和包含两个不同字符串的Address和zip代码的Address。我创建了一个IRepositoryC# 当实体的ID是不同类型(string/int)时,如何创建CRUD存储库?,c#,sql,.net,database,entity-framework,C#,Sql,.net,Database,Entity Framework,我对RESTAPI非常陌生,我想知道创建CRUD存储库的最佳方法是什么,该存储库可以处理具有不同类型ID/主键的实体:带有int的Car、带有字符串的Person和包含两个不同字符串的Address和zip代码的Address。我创建了一个IRepository public interface IRepository<EntityBase> { Task<PayoutResult> Insert(EntityBase entity);
public interface IRepository<EntityBase>
{
Task<PayoutResult> Insert(EntityBase entity);
bool EntityExists(EntityBase entity);
}
并使所有模型实现EntityBase,但我不确定当它们都有三种不同的id类型时,BaseEntity应该是什么样子 我建议你有这样的智慧:
public interface IEntity<TKey> where TKey : IEquatable<TKey>
{
TKey Id { get; set; }
}
public interface IRepository<TEntity, in TKey> where TEntity : IEntity<TKey> where TKey : IEquatable<TKey>
{
(...)
Task<TEntity> GetByIdAsync(TKey id);
void Insert(TEntity entity);
(...)
}
我建议你有这样的智慧:
public interface IEntity<TKey> where TKey : IEquatable<TKey>
{
TKey Id { get; set; }
}
public interface IRepository<TEntity, in TKey> where TEntity : IEntity<TKey> where TKey : IEquatable<TKey>
{
(...)
Task<TEntity> GetByIdAsync(TKey id);
void Insert(TEntity entity);
(...)
}
使用泛型将使您开始学习。TId指定id的类型
public class EntityBase<TId>
{
public TId Id {get; set;}
}
public interface IRepository<TId>
{
Task<PayoutResult> Insert(EntityBase<TId> entity);
bool EntityExists(EntityBase<TId> entity);
}
就我个人而言,我讨厌通用存储库。为什么?这是一个滑坡。我觉得这是一个糟糕的设计选择。我们有一个到处都是这样的应用程序,维护它是一场噩梦。通用存储库也不遵循该接口
使用泛型将使您开始学习。TId指定id的类型
public class EntityBase<TId>
{
public TId Id {get; set;}
}
public interface IRepository<TId>
{
Task<PayoutResult> Insert(EntityBase<TId> entity);
bool EntityExists(EntityBase<TId> entity);
}
就我个人而言,我讨厌通用存储库。为什么?这是一个滑坡。我觉得这是一个糟糕的设计选择。我们有一个到处都是这样的应用程序,维护它是一场噩梦。通用存储库也不遵循该接口
如果答案解决了您的问题,建议您接受它。如果答案解决了你的问题,建议你接受它。否则,请解释缺失的内容或您需要的内容。