如何在插入数据并获取返回的id后修复DapperExtensions错误 [英] How to fix DapperExtensions error after I Insert data and get the returned id
本文介绍了如何在插入数据并获取返回的id后修复DapperExtensions错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用Dapper-Expantions将数据拉入和推送到数据库
我使用unsigned int
id作为数据库和类中的主键。
我的班级是这样的
public class Product {
[Column("id")]
public uint Id { get; set; }
}
我的映射器类如下所示
public class ProductMap : ClassMapper<Product>
{
public ProductMap()
{
Table("Product");
this.Map(typeof(Product).GetProperty("Id")).Key(KeyType.Identity);
}
}
我像这样插入数据
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'.'`
}
}
当我将数据插入到数据库中时,项被插入到数据库中时没有问题,但是INSERT函数一直返回以下错误:
‘类型为’System.Int32‘的对象不能转换为类型 ‘System.UInt32’.
我如何才能修复它?
推荐答案
Dapper扩展的dynamic Insert<T>
方法可以返回任何类型的新生成的ID。
它使用/对指定实体执行插入查询,返回主键。
/如果实体只有一个键,则只返回值。
/如果实体有复合键,则返回IDicary<;字符串,Object&>键值。
/如果KeyType为GUID或Identity,则实体的密钥值也将更新。
SqlGeneratorImpl
类中的IdentitySql
方法完成此操作。这可以通过以下代码进行确认:
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);
}
如您所说,插入操作正在正常进行。然后Dapper扩展提取新生成的标识值,并尝试将其分配给您的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
}
这篇关于如何在插入数据并获取返回的id后修复DapperExtensions错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文