98

Using , how can I insert a C# List to database. Previously without dapper I used the below code to insert the List values to database.

try
{                
    connection.Open();

    for (int i = 0; i < processList.Count; i++)
    {
        string processQuery = "INSERT INTO PROCESS_LOGS VALUES (@Id, @st_Time, @ed_Time, @td_Time)";
        command = new SqlCommand(processQuery, connection);
        command.Parameters.Add("Id", SqlDbType.Int).Value = processList[i].ID;
        command.Parameters.Add("st_Time", SqlDbType.DateTime).Value = processList[i].ST_TIME;
        command.Parameters.Add("ed_Time", SqlDbType.DateTime).Value = processList[i].ED_TIME;
        command.Parameters.Add("td_Time", SqlDbType.DateTime2).Value = processList[i].TD_TIME;
        dataReader.Close();
        dataReader = command.ExecuteReader();
    }

    connection.Close();
}
catch (SqlException ex)
{
    //--Handle Exception
}

I'm familiar with fetching the data using dapper but this is my first try using insert query.

I tried the below code, using Exceute linked to query but stuck up with looping; I think using dapper tool, there is no need for looping statement.

connection.Execute(processQuery ... );

EDIT:

class ProcessLog
    {
        public int ID { get; set; }
        public DateTime ST_TIME { get; set; }
        public DateTime ED_TIME { get; set; }
        public DateTime TD_TIME { get; set; }
        public string frequency { get; set; }
    }

Please advice on this. FYI: I'm using SQL Server 2008.

4

3 回答 3

163

你必须做一些不同的事情。在 Dapper 中,它匹配与 SQL 参数相同的约定 AKA 属性或字段名称。所以,假设你有一个MyObject

public class MyObject
{
    public int A { get; set; }

    public string B { get; set; }
}

并假设processList = List<MyObject>,你想这样做

foreach (var item in processList)
{
    string processQuery = "INSERT INTO PROCESS_LOGS VALUES (@A, @B)";        
    connection.Execute(processQuery, item);
}

请注意,MyObject属性名称 A 和 B 与 SQL 参数名称 @A 和 @B 匹配。

如果您不想重命名对象,则可以使用匿名类型而不是具体类型来进行映射:

foreach (var item in processList)
{
    string processQuery = "INSERT INTO PROCESS_LOGS VALUES (@A, @B)";        
    connection.Execute(processQuery, new { A = item.A, B = item.B });
}

编辑:

根据 Marc Gravell 的评论,您还可以让 Dapper 为您执行循环:

string processQuery = "INSERT INTO PROCESS_LOGS VALUES (@A, @B)";        
connection.Execute(processQuery, processList);
于 2013-06-17T15:08:06.170 回答
24

我相信批量插入比迭代列表并一一插入要好。

SqlTransaction trans = connection.BeginTransaction();

connection.Execute(@"
insert PROCESS_LOGS(Id, st_Time, ed_Time, td_Time)
values(@Id, @st_Time, @ed_Time, @td_Time)", processList, transaction: trans);

trans.Commit();

参考:https ://stackoverflow.com/a/12609410/1136277

于 2017-04-12T18:02:31.393 回答
4

使用 Dapper.Contrib https://dapper-tutorial.net/insert#example---insert-single!您可以毫不费力地在 db 中插入对象列表。

于 2020-05-06T12:33:37.437 回答