c# - 有一个带有 CRUD 实现的基实体类和一个可以由实现它的类更改的主键 ID
问题描述
为了不为每个实体重写基本 CRUD,我想使用可以由任何其他实体实现的基本 CRUD 操作来实现一个基本实体类。
问题是我正在使用Dapper 与 Dapper.Contrib 进行映射,并且我的数据库表主键从未命名为 Id - 我不能使用 Dapper 映射器。
我想不出一种方法来为每个实体提供一个简单 CRUD 的基类。
解决方案
尽管@Athanasios Kataras 的回答有效,但我仍然使用 Dapper.contrib 扩展,因为我认为它更清楚。
我使用了 Dapper.contrib 并创建了一个 Base Repository 类,然后其他所有存储库都使用该类。主键(ID)是通过使用 Dapper 在实体([Key]、[ExplicitKey])上提供的数据注释来处理的。
一些实现 Base Repository 的存储库类的示例:
public class ACRepository : BaseRepository<ACEntity>, IACRepository
{
private readonly IDbConnection _dbConnection;
public ACRepository(IDbConnection _dbconn) : base(_dbconn)
{
_dbConnection = _dbconn;
}
// Some other methods that require more complicated queries
}
基础存储库类:
using Dapper.Contrib.Extensions;
public class BaseRepository<T> : IBaseRepository<T> where T : class
{
private readonly IDbConnection _dbConnection;
public BaseRepository(IDbConnection _dbconn)
{
_dbConnection = _dbconn;
}
public async Task Add(T entity)
{
var result = await _dbConnection.InsertAsync(entity);
}
public async Task<bool> Delete(T entity)
{
return await _dbConnection.DeleteAsync(entity);
}
public async Task<bool> Update(T entity)
{
return await _dbConnection.UpdateAsync(entity);
}
public async Task<T> GetById(object id)
{
return await _dbConnection.GetAsync<T>(id);
}
public async Task<IEnumerable<T>> GetAll()
{
return await _dbConnection.GetAllAsync<T>();
}
}
一个实体:
using Dapper.Contrib.Extensions;
[Table("table_name")]
public class SquawkRegisterPMEEntity
{
[ExplicitKey]
public string SomeKey { get; set; }
[Key]
public int SomeOtherKey{ get; set; }
public string SomeProperty { get; set; }
public string SomeProperty1 { get; set; }
}
如果值是由数据库生成的,则使用[Key] 。
[ExplicitKey]在手动指定 Id 时使用。