使用dapper.NET C#插入列表

Vin*_*uet 6 c# sql list dapper

我想在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);                
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我想知道如何使用Dapper插入我的列表,我不想迭代列表并逐个保存,我想在一个请求中插入所有这些.

Pie*_*iez 12

您可以像插入一行一样插入这些:

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);                
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Dapper将查找以SQL参数命名的类成员(@ Id,@ ObjectType,@ Content,@ PreConContent)并相应地绑定它们.

  • 尝试这个答案,看看它是否有助于提高性能:http://stackoverflow.com/a/12609410/1166719。顺便说一下,嗨!好久不见 :) (2认同)
  • 这会为列表中的每个项目创建一个请求,从而无法解决问题。 (2认同)