我想在SQL表中插入对象列表。
我知道这个问题here,但我不明白。
这是我的班级:
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插入我的列表,我不想迭代列表并逐个保存,我想在一个请求中插入所有这些
答案 0 :(得分:11)
您可以像插入一行一样插入这些:
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 :(得分:1)
您需要传递一个表值参数
1.在sql数据库中创建表类型
2.创建DynamicParameters并将数据表(新值)添加到其中
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#:
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
答案 2 :(得分:0)
您只需将SQL更改为有效的插入参数,其参数与您类的属性名称相匹配。
INSERT INTO MyObject VALUES(@Id, @ObjectType, @Content, @PreviewContent)
或者,如果您需要指定表格列(例如,这些列不是表格中的所有列):
INSERT INTO MyObject (Id, ObjectType, Content, PreviewContent)
VALUES(@Id, @ObjectType, @Content, @PreviewContent)
答案 3 :(得分:0)
您可以使用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();
}
}
答案 4 :(得分:0)
如果您需要新的命名或组合来源:
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
}));