smerlung
smerlung

Reputation: 1519

DapperExtensions MySQL INSERT set ID

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?

Upvotes: 2

Views: 1141

Answers (1)

smerlung
smerlung

Reputation: 1519

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<>);

Upvotes: 5

Related Questions