简体   繁体   English

使用 dapper.NET C# 插入列表

[英]Insert a list using dapper.NET C#

I'd like to insert a list of objects in an SQL table.我想在 SQL 表中插入一个对象列表。

I know this question here but I don't understand.在这里知道这个问题但我不明白。

Here is my class :这是我的课:

public class MyObject 
{
    public int? ID { get; set; }
    public string ObjectType { get; set; }
    public string Content { get; set; }
    public string PreviewContent { get; set; }

    public static void SaveList(List<MyObject> lst)
    {
        using (DBConnection connection = new DBConnection())
        {
            if (connection.Connection.State != ConnectionState.Open)
                connection.Connection.Open();

            connection.Connection.Execute("INSERT INTO [MyObject] VALUE()",lst);                
        }
    }
}

I'd like to know how could I insert my list using Dapper, I don't want to iterate on the list and save them one by one, I would like to insert all of them in one request.我想知道如何使用 Dapper 插入我的列表,我不想在列表上迭代并一一保存,我想在一个请求中插入所有这些。

You can insert these just as you would INSERT a single line:您可以像插入单行一样插入这些:

public class MyObject 
{
    public int? ID { get; set; }
    public string ObjectType { get; set; }
    public string Content { get; set; }
    public string PreviewContent { get; set; }

    public static void SaveList(List<MyObject> lst)
    {
        using (DBConnection connection = new DBConnection())
        {
            if (connection.Connection.State != ConnectionState.Open)
                connection.Connection.Open();

            connection.Connection.Execute("INSERT INTO [MyObject] (Id, ObjectType, Content, PreviewContent) VALUES(@Id, @ObjectType, @Content, @PreviewContent)", lst);                
        }
    }
}

Dapper will look for class members named after your SQL parameters (@Id, @ObjectType, @Content, @PreviewContent) and bind them accordingly. Dapper 将查找以您的 SQL 参数(@Id、@ObjectType、@Content、@PreviewContent)命名的类成员并相应地绑定它们。

You need pass a table-value parameter.您需要传递一个表值参数。
1. Create table type in your sql database. 1. 在你的 sql 数据库中创建表类型。
2. Create DynamicParameters and add the datatable (new values) to it. 2. 创建 DynamicParameters 并向其添加数据表(新值)。
3. Execute. 3. 执行。

SQL:查询语句:

CREATE TYPE [dbo].[tvMyObjects] AS TABLE(
    [ID] INT,
    [ObjectType] [varchar](70), /*Length on your table*/
    [Content] [varchar](70), /*Length on your table*/
    [PreviewContent] [varchar](70) /*Length on your table*/
)

C#: C#:

var dynamicParameters = new DynamicParameters();
dynamicParameters.Add("@MyObjects", lst
    .AsTableValuedParameter("dbo.tvMyObjects", new[] 
    {
        "ID" ,
        "ObjectType",
        "Content", 
        "PreviewContent"
    }));

connection.Connection.Execute(@"
    INSERT INTO [MyObject] (Id, ObjectType, Content, PreviewContent) 
    SELECT Id,
           ObjectType,
           Content,
           PreviewContent
    FROM   @MyObjects", dynamicParameters);

More info: https://www.codeproject.com/Articles/835519/Passing-Table-Valued-Parameters-with-Dapper更多信息: https : //www.codeproject.com/Articles/835519/Passing-Table-Valued-Parameters-with-Dapper

You would just change your SQL to a valid insert statment that has parameters matching the names of the properties on your class.您只需将 SQL 更改为有效的插入语句,该语句的参数与您的类的属性名称匹配。

INSERT INTO MyObject VALUES(@Id, @ObjectType, @Content, @PreviewContent)

Or if you need to specify the table columns (where these aren't all the columns in the table, for example):或者,如果您需要指定表列(例如,这些列不是表中的所有列):

INSERT INTO MyObject (Id, ObjectType, Content, PreviewContent)
VALUES(@Id, @ObjectType, @Content, @PreviewContent)

You can use the Dapper.Contrib extensions to simplify the code.您可以使用 Dapper.Contrib 扩展来简化代码。 I've found this works well for a few hundred records, but for very large inserts, I switch to SqlBulkCopy.我发现这适用于几百条记录,但对于非常大的插入,我切换到 SqlBulkCopy。 The synchronous version is Insert instead of InsertAsync (as you'd guess).同步版本是 Insert 而不是 InsertAsync(如您所料)。 Make sure your entities are named as Dapper expects and have a primary key, Id, or, add annotations for table name and key to your entity.确保您的实体按照 Dapper 期望的方式命名,并具有主键、Id,或者为您的实体添加表名和键的注释。

using using Dapper.Contrib.Extensions; //Git

public async Task SaveChangesAsync(IList<MyEntity> myEntityValues)
{
     var conn = new SqlConnection(myconnectionString);
     if(conn.State != ConnectionState.Open)
         conn.Open();
     await conn.InsertAsync(myEntityValues);
     if (conn.State != ConnectionState.Closed)
     {
        conn.Close();
        conn.Dispose();
      }
}

In case you need new naming or combined sources:如果您需要新的命名或组合源:

await connection.ExecuteAsyncWithRetry(SqlSave,
     list.Select(x => 
            new
            {
                x.ID,
                SomeNew = NewSource.SomeNew,  // From other source
                NameNew = x.NameOld,  // New naming
                x.ObjectType,
                x.Content,
                x.ContentList = String.Join(",", x.Content)  // Data transform
            }));

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

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