简体   繁体   English

当表的列数超过 class 时使用 Dapper

[英]Using Dapper when table has more columns than class

In Dapper how do you ignore a table column during an insert?在 Dapper 中,如何在插入期间忽略表列?

I have a class with properties A,B,C and have a List of these.我有一个 class,其属性为 A、B、C,并且有这些的列表。

Presume something like假设类似

class DTO 
{
    string A;
    string B;
    string C;
}

and the list is of type列表是类型

List myList = new List<DTO>()

So with a line of sql like this to bulk insert the list into my table因此,像这样使用 sql 行将列表批量插入到我的表中

sql="INSERT INTO TABLE VALUES (@A,  @B, @C)";
conn.Execute(sql, myList)

It works fine and inserts all my data when my table also has columns A,B,C.当我的表也有列 A、B、C 时,它工作正常并插入我的所有数据。

But when my table has more columns, eg A,B,C,DI get the error: Column name or number of supplied values does not match table definition但是当我的表有更多列时,例如 A、B、C、DI 得到错误:列名或提供值的数量与表定义不匹配

I know how to ignore class properties using the Dapper Contrib library, but not the other way round.我知道如何使用 Dapper Contrib 库忽略 class 属性,但反之则不然。

How can I do this?我怎样才能做到这一点?

Thanks.谢谢。

You have to enumerate your columns specifically, as in:您必须具体枚举您的列,如:

sql="INSERT INTO TABLE (column1name, column2name, column3name) VALUES (@A,  @B, @C)";

Alternatively, if your DTO contains a primary key, you can decorate your DTO with the following attributes:或者,如果您的 DTO 包含主键,您可以使用以下属性修饰 DTO:

[Table("TableName")]
class DTO 
{
    [Key]
    int id;
    string A;
    string B;
    string C;
}

and use Insert() from Dapper.Contrib .并使用Dapper.Contrib中的Insert()

connection.Insert(dto);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM