当 table 的列多于 class 时使用 Dapper
Using Dapper when table has more columns than class
在 Dapper 中,如何在插入期间忽略 table 列?
我有一个 class 具有属性 A、B、C 并且有这些的列表。
假设类似
class DTO
{
string A;
string B;
string C;
}
并且列表的类型是
List myList = new List<DTO>()
所以用这样一行 sql 将列表批量插入到我的 table
sql="INSERT INTO TABLE VALUES (@A, @B, @C)";
conn.Execute(sql, myList)
当我的 table 也有 A、B、C 列时,它工作正常并插入我的所有数据。
但是当我的 table 有更多列时,例如A、B、C、D 我收到错误:列名或提供的值数量与 table 定义
不匹配
我知道如何使用 Dapper Contrib 库忽略 class 属性,但反之则不然。
我该怎么做?
谢谢。
您必须具体枚举您的列,如:
sql="INSERT INTO TABLE (column1name, column2name, column3name) VALUES (@A, @B, @C)";
或者,如果您的 DTO 包含主键,您可以使用以下属性装饰您的 DTO:
[Table("TableName")]
class DTO
{
[Key]
int id;
string A;
string B;
string C;
}
并使用 Dapper.Contrib 中的 Insert()
。
connection.Insert(dto);
在 Dapper 中,如何在插入期间忽略 table 列?
我有一个 class 具有属性 A、B、C 并且有这些的列表。
假设类似
class DTO
{
string A;
string B;
string C;
}
并且列表的类型是
List myList = new List<DTO>()
所以用这样一行 sql 将列表批量插入到我的 table
sql="INSERT INTO TABLE VALUES (@A, @B, @C)";
conn.Execute(sql, myList)
当我的 table 也有 A、B、C 列时,它工作正常并插入我的所有数据。
但是当我的 table 有更多列时,例如A、B、C、D 我收到错误:列名或提供的值数量与 table 定义
不匹配我知道如何使用 Dapper Contrib 库忽略 class 属性,但反之则不然。
我该怎么做?
谢谢。
您必须具体枚举您的列,如:
sql="INSERT INTO TABLE (column1name, column2name, column3name) VALUES (@A, @B, @C)";
或者,如果您的 DTO 包含主键,您可以使用以下属性装饰您的 DTO:
[Table("TableName")]
class DTO
{
[Key]
int id;
string A;
string B;
string C;
}
并使用 Dapper.Contrib 中的 Insert()
。
connection.Insert(dto);