插入数据并获取返回的 id 后如何修复 DapperExtensions 错误

2023-12-03

I use 简洁的扩展将数据拉取和推送到数据库

I use unsigned intid 作为我的主键database并在class以及。 我的课看起来像这样

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'.'`
    }
}

当我将数据插入数据库时​​,该项目会毫无问题地插入数据库,但是插入函数不断返回以下错误:

'System.Int32'类型的对象无法转换为类型 '系统.UInt32'。'

我怎样才能解决这个问题?


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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

插入数据并获取返回的 id 后如何修复 DapperExtensions 错误 的相关文章

随机推荐