使用dapper.NET C#插入列表 [英] Insert a list using dapper.NET C#

查看:189
本文介绍了使用dapper.NET C#插入列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在SQL表中插入对象列表.

I'd like to insert a list of objects in an SQL table.

我在此处知道了这个问题,但我不理解.

I know this question here but I don't understand.

这是我的课程:

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插入列表,我不想在列表上进行迭代并一一保存,我想将它们全部插入一个请求中.

I'd like to know how could I insert my list using Dapper, I don't want to iterate on the list and save them one by one, I would like to insert all of them in one request.

推荐答案

您可以插入这些内容,就像插入单行一样:

You can insert these just as you would INSERT a single line:

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)命名的类成员,并进行相应的绑定.

Dapper will look for class members named after your SQL parameters (@Id, @ObjectType, @Content, @PreviewContent) and bind them accordingly.

这篇关于使用dapper.NET C#插入列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆