Search code examples
c#postgresqldappernpgsqldapper-simplecrud

Dapper / SimpleCRUD Insert with VARCHAR primary key throwing FormatException - "The string was not in a correct format"


I am trying to insert into a postgresql database using dapper and simplecrud.

My entity has a VARCHAR primary key, which I understand means that I have to include the [Key] and [Required] tags within my POCO.

[Table("tube_data")]
class Tube : IEntity
{
    //my primary key (name matches column name)
    [Dapper.Key] [Dapper.Required] 
    public string tube_nr { get; } 

    //Constructors (probably not important)
    private Tube()
    {
    }

    public Tube(string tube_nr)
    {
        this.tube_nr = tube_nr;
    }

    //more code... just nullable properties (ints, floats and strings)
}

When I execute the function using

    _conn.Insert<Tube>(t);

I get a System.FormatException. "The string was not in a correct format". Looking at the stack trace, I can see that Dapper is calling System.Convert.ToInt64()

I have other entities with auto-incrementing primary keys, which work without a problem (so I know the NpgSqlConnection is working fine). In fact, all of my VARCHAR PK entities fail, while all of my auto-incrementing PK entities succeed.

I have a lot of properties, so I don't want to write out the SQL manually if I can avoid it.

How do I get SimpleCRUD to work properly with VARCHAR/string primary keys? I thought the [Key][Required] tags would do the trick.


Solution

  • Try Dapper.Contrib with [ExplicitKey]. This works with both string and int key.

    ExplicitKey: Specify the property as a key explicitly which is not automatically generated by the database.