问题描述
使用的问题,如何插入 C#列表
到数据库。以前没有 dapper ,我使用下面的代码 将列表值插入数据库 。
Using dapper, 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
}
我熟悉使用 dapper 获取数据,但这是我第一次尝试使用插入查询。
I'm familiar with fetching the data using dapper but this is my first try using insert query.
我尝试使用下面的代码,使用链接到查询的 Exceute
,但陷入了循环;我认为使用dapper工具不需要循环语句。
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 ... );
编辑:
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; }
}
请对此提供建议。 仅供参考::我正在使用 SQL Server 2008
。
Please advice on this. FYI: I'm using SQL Server 2008
.
推荐答案
您必须做一些不同的事情。在Dapper中,它与约定的AKA属性或与SQL参数相同的字段名称匹配。因此,假设您有一个 MyObject
:
You'd have to do it a little differently. In Dapper, it matches on convention AKA property or field names being identical to SQL parameters. So, assuming you had a 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匹配。
Note that the MyObject
property names A and B match the SQL parameter names @A and @B.
如果您不想重命名对象,则可以使用匿名类型来完成。而不是具体类型的映射:
If you don't want to rename objects, you can use anonymous types to do the mappings instead of concrete types:
foreach (var item in processList)
{
string processQuery = "INSERT INTO PROCESS_LOGS VALUES (@A, @B)";
connection.Execute(processQuery, new { A = item.A, B = item.B });
}
编辑:
Per Marc Gravell的注释,您也可以让Dapper为您做循环:
Per Marc Gravell's comment, you can also have Dapper do the loop for you:
string processQuery = "INSERT INTO PROCESS_LOGS VALUES (@A, @B)";
connection.Execute(processQuery, processList);
这篇关于如何使用Dapper.NET将C#列表插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!