The dynamic Insert<T>Dapper Extensions 的方法可以返回新生成的任意类型的 ID。
/// 对指定实体执行插入查询,返回主键。
/// 如果实体只有一个键,则仅返回值。
/// 如果实体有复合键,则返回 IDictionary 和键值。
/// 如果 KeyType 是 Guid 或 Identity,则实体的键值也将被更新。
它这样做是通过IdentitySql中的方法SqlGeneratorImpl
class.
可以通过以下代码确认这一点:
public class Product
{
public Guid Id { get; set; }
public string Name { get; set; }
public bool Active { get; set; }
}
public sealed class ProductMapper : ClassMapper<Product>
{
public ProductMapper()
{
Schema("dbo");
Table("Products");
Map(x => x.Id).Key(KeyType.Guid);
AutoMap();
}
}
Product product = new Product();
product.Name = "Product 1";
product.Active = true;
using(SqlConnection conn = new SqlConnection(connString))
{
DapperExtensions.DapperExtensions.Insert<Product>(conn, product, null, null);
Guid customerID = product.Id;
product = null;
product = DapperExtensions.DapperExtensions.Get<Product>(conn, customerID, null, null);
}
正如您所说,INSERT 操作运行良好。然后是 Dapper 扩展extract新生成的身份值并尝试将其分配给您Product.Id
财产。
现在,返回的数据类型(列值)是int
已签署。数据类型Id
财产是uint
这是未签名的。尽管两种数据类型的长度相同,但它们可以保存的数据类型(有符号和无符号)不同,因此会出现错误。
您应该更改您的数据类型Id
财产给int
像下面这样:
public int Id { get; set; }
正如您在回答中所说,您必须保留财产uint
,以下是我的建议:
将额外的属性添加到您的类中,就像下面的持有者/副本一样:
public class Product {
[Column("id")]
public int Id { get; set; }//Map this as Identity.
public uint IdCopy { get { return Convert.ToUInt32(Id); } }//Readonly; Exclude this from mapping
}