簡體   English   中英

使用 dapper.NET C# 插入列表

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

我想在 SQL 表中插入一個對象列表。

在這里知道這個問題但我不明白。

這是我的課:

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);                
        }
    }
}

我想知道如何使用 Dapper 插入我的列表,我不想在列表上迭代並一一保存,我想在一個請求中插入所有這些。

您可以像插入單行一樣插入這些:

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 將查找以您的 SQL 參數(@Id、@ObjectType、@Content、@PreviewContent)命名的類成員並相應地綁定它們。

您需要傳遞一個表值參數。
1. 在你的 sql 數據庫中創建表類型。
2. 創建 DynamicParameters 並向其添加數據表(新值)。
3. 執行。

查詢語句:

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#:

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);

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

您只需將 SQL 更改為有效的插入語句,該語句的參數與您的類的屬性名稱匹配。

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

或者,如果您需要指定表列(例如,這些列不是表中的所有列):

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

您可以使用 Dapper.Contrib 擴展來簡化代碼。 我發現這適用於幾百條記錄,但對於非常大的插入,我切換到 SqlBulkCopy。 同步版本是 Insert 而不是 InsertAsync(如您所料)。 確保您的實體按照 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();
      }
}

如果您需要新的命名或組合源:

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