Does dapper.contrib support primary key in varchar type?

dapper

Question

I am new to Dapper, trying to write some code to test Dapper.Contrib.

[Dapper.Contrib.Extensions.Table("Cat")]
public class Cat
{
    [Dapper.Contrib.Extensions.Key]
    public string catid {get;set;}
    public string catName {get;set;}
}
...
Cat cat = new Cat(){catid="somecharmaybe", catName="testcat"}
conn.Insert(cat);

When I run the application, following exception is thrown

can not insert null value to primary key catid

Can anyone give me some advice?

Accepted Answer

can not insert null value to primary key catid

The error says you cant insert null value on catid because dapper understand that this is identity key which is generated by the database to solve this use DapperExtension

public class Cat
{
    public string catid {get;set;}
    public string catName {get;set;}
}

public class CatMap : ClassMapper<Cat>
{
   public CatMap()
   {
       Table("Cat")
       Map(s=>s.CatId).Key(KeyType.Assigned);
       AutoMap();
   } 
}

i hope it help, if anyone has better solution kindly post it here thank you.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why