Dapper / SimpleCRUD 插入 VARCHAR 主键抛出 FormatException - “字符串格式不正确”

问题描述 投票:0回答:2

我正在尝试使用 dapper 和 simplecrud 插入到 postgresql 数据库中。

我的实体有一个 VARCHAR 主键,我理解这意味着我必须在我的 POCO 中包含 [Key] 和 [Required] 标签。

[Table("tube_data")]
class Tube : IEntity
{
    //my primary key (name matches column name)
    [Dapper.Key] [Dapper.Required] 
    public string tube_nr { get; } 

    //Constructors (probably not important)
    private Tube()
    {
    }

    public Tube(string tube_nr)
    {
        this.tube_nr = tube_nr;
    }

    //more code... just nullable properties (ints, floats and strings)
}

当我执行函数时使用

    _conn.Insert<Tube>(t);

我得到一个 System.FormatException。 “字符串格式不正确”。查看堆栈跟踪,我可以看到 Dapper 正在调用 System.Convert.ToInt64()

我有其他具有自动递增主键的实体,它们可以正常工作(所以我知道 NpgSqlConnection 工作正常)。事实上,我所有的 VARCHAR PK 实体都失败了,而我所有的自动递增 PK 实体都成功了。

我有很多属性,所以如果可以避免,我不想手动写出SQL。

如何让 SimpleCRUD 与 VARCHAR/string 主键一起正常工作?我认为 [Key][Required] 标签可以解决问题。

c# postgresql dapper npgsql dapper-simplecrud
2个回答
1
投票

尝试使用 [ExplicitKey] Dapper.Contrib。这适用于字符串和 int 键。

ExplicitKey:显式指定属性为键,不是由数据库自动生成的。


0
投票

测试并为我工作,

  • 将 Dapper.Contrib 与 [ExplicitKey, Required] 一起使用
  • 插入时定义键类型:_conn.Insert(t);
© www.soinside.com 2019 - 2024. All rights reserved.