c# - 当实体的 id 是不同类型(string/int)时,如何创建 CRUD 存储库?

标签 c# sql .net database entity-framework

我是 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/

相关文章:

Java比较类的元素

c# - 从 Main 函数最大化窗口?

C# Regex - 接受字符串中的空格

c# - 将python转换为c#的工具

c# - 如何修复 "Object reference not set to an instance of an object"?

.net - 从 RichTextBox 复制文本及其格式

c# - 为什么使用 Activator.CreateInstance 创建的实例不解析引用?

c# - 控制台上的 WriteLine 但采用复古风格

c# - 使用 SUM() 将 SQL 语句转换为 Linq/Entity Framework

sql - 在数字列表之间拆分 float