DapperExtensions MySQL INSERT集ID

sme*_*ung 2 c# mysql dapper dapper-extensions

如果我上课:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用Dapper / DapperExtensions将其插入到相应的MySQL表中:

var person = new Person { Id = 10, Name = "Bobby" };
connection.Insert(person);
Run Code Online (Sandbox Code Playgroud)

假设MySQL中的Id列设置为AUTO_INCREMENT且该表为空。然后将Id值10更改为1。

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

sme*_*ung 5

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

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

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

DapperExtensions.DapperExtensions.DefaultMapper = typeof(PrimaryKeyAssignedClassMapper<>);
Run Code Online (Sandbox Code Playgroud)