DapperExtensions MySQL 插入集 ID

DapperExtensions MySQL INSERT set ID

如果我有 class:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

然后我尝试使用 Dapper/DapperExtensions:

将其插入相应的 MySQL table
var person = new Person { Id = 10, Name = "Bobby" };
connection.Insert(person);

假设 MySQL 中的 Id 列设置为 AUTO_INCREMENT 且 table 为空。然后在某个地方将 Id 值 10 更改为 1。

是否可以使用 Dapper/DapperExtensions 插入正确的 Id 10?

我发现解决方案很简单。解决方案是使用自定义 class 映射器。 (下面代码中的 EntityBase class 是我系统中所有数据库实体的基础 class)

public class PrimaryKeyAssignedClassMapper<T> : ClassMapper<T> where T : EntityBase
{
    public PrimaryKeyAssignedClassMapper()
    {
        base.Map(m => m.Id).Key(KeyType.Assigned);
        base.AutoMap();
    }
}

然后在调用 Insert 方法之前的某个时刻,我添加了

DapperExtensions.DapperExtensions.DefaultMapper = typeof(PrimaryKeyAssignedClassMapper<>);