2

If I have a class:

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

And I try to insert this into a corresponding MySQL table using Dapper/DapperExtensions:

var person = new Person { Id = 10, Name = "Bobby" };
connection.Insert(person);

Assuming the Id column in MySQL is set to AUTO_INCREMENT and that the table is empty. Then somewhere along the way the Id value of 10 is changed into 1.

Is it possible, using Dapper/DapperExtensions, to insert the correct Id of 10?

smerlung
  • 1,459
  • 1
  • 13
  • 32

1 Answers1

5

I turned out that the solution was very simple. The solution was using a custom classmapper. (The EntityBase class, in the code below, is a base class for all database entities in my system)

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

And then at somepoint before calling the Insert method, I added

DapperExtensions.DapperExtensions.DefaultMapper = typeof(PrimaryKeyAssignedClassMapper<>);
smerlung
  • 1,459
  • 1
  • 13
  • 32