1

我使用Dapper-Extensions将数据拉取并推送到数据库

我使用unsigned intid 作为我在数据库中的主键。我的课看起来像这样

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' 类型的对象无法转换为'System.UInt32' 类型。

我怎么可能解决这个问题?

4

2 回答 2

1

Dapper Extensions的dynamic Insert<T>方法可以返回新生成的任意类型的 ID。

/// 对指定实体执行插入查询,返回主键。
/// 如果实体只有一个键,则只返回值。
/// 如果实体有复合键,则返回 IDictionary<string, object> 和键值。
/// 如果 KeyType 是 Guid 或 Identity,实体的键值也会更新。

它使用类中的IdentitySql方法来做到这一点SqlGeneratorImpl
这可以通过以下代码确认:

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 Extensions提取新生成的身份值并尝试将其分配给您的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
}
于 2019-05-21T06:38:53.133 回答
0

我真的需要将我的数据 ID 存储为uint并找到解决该int32uint转换错误的方法。

DapperImplementor.cs class, 函数内部public dynamic Insert<T> {...}

有一个变量int identityInt = 0;用来保存 id 在分配给对应的对象 id 之前

在我将其类型更改为后问题已解决uint identityInt = 0;

于 2019-05-22T18:25:42.537 回答