I use Dapper-Extentions to pull and push data to database
I use unsigned int id as my Primary key in database and in the class as well.
my class looks like this
public class Product {
[Column("id")]
public uint Id { get; set; }
}
My Mapper Class looks like this
public class ProductMap : ClassMapper<Product>
{
public ProductMap()
{
Table("Product");
this.Map(typeof(Product).GetProperty("Id")).Key(KeyType.Identity);
}
}
I insert data like this
using DapperExtensions;
public virtual uint Add(T item)
{
using (conn)
{
return Convert.ToUInt32(conn.Insert<T>(item)); // System.ArgumentException: 'Object of type 'System.Int32' cannot be converted to type 'System.UInt32'.'`
}
}
When I insert data into database, the item get inserted into the database without issues, However the Insert function keeps returning the following error :
'Object of type 'System.Int32' cannot be converted to type 'System.UInt32'.'
How can I possibly fix that ?
The
dynamic Insert<T>method of Dapper Extensions can return the newly generated ID of any type.It does this with
IdentitySqlmethod inSqlGeneratorImplclass.This can be confirmed with following code:
As you said, INSERT operation is happening fine. Then Dapper Extensions extract the newly generated identity value and tries to assign it to your
Product.Idproperty.Now, datatype of what is returned (column value) is
intwhich is signed. Datatype ofIdproperty isuintwhich is unsigned. Though the length of both the data types is same, type of the data (signed and unsigned) they can hold is different and hence the error.You should change data type of your
Idproperty tointlike below:As you said in your answer, you have to keep the property
uint, following is what I propose:Add an extra property to your class just as a holder/copy like below: