eltropico
eltropico

Reputation: 13

Executing Insert Statement with Dapper

I am trying to use the method explained by @MarcGravell in the below post and comments

How to insert a C# List to database using Dapper.NET

I am trying to go from

        string sql2 = string.Format(@"INSERT INTO #cusipSedolList (cusipSedol) values (@A)");

        IDbConnection con = new SqlConnection(_connectionString);

        using (con)
        {
            con.Open();
            foreach (var cusipSedol in cusipSedolsParameter)
            {
                con.Execute(sql2, new { A = cusipSedol.CusipSedol });
            }

        }

to

        string sql2 = string.Format(@"INSERT INTO #cusipSedolList (cusipSedol) values (@CusipSedol)");

        IDbConnection con = new SqlConnection(_connectionString);

        using (con)
        {
            con.Open();
            con.Execute(sql2, new {cusipSedolsParameter});

        }

with

       var cusipSedolsParameter = new List<CusipSedols>();

       public class CusipSedols
       {
           public string CusipSedol { get; set; }
       }

but I am getting the error that I have to declare @CusipSedol if it has more than one CusipSedol.

Upvotes: 1

Views: 1357

Answers (1)

Michael Petito
Michael Petito

Reputation: 13161

In your second example, you pass the argument new {cusipSedolsParameter} which is an anonymous type object with a single member named cusipSedolsParameter.

Instead, you just want to pass your list. Your call should look like:

con.Execute(sql2, cusipSedolsParameter);

Then Dapper will enumerate over your list and perform your query for each entry, matching query parameters against the properties of the type of the entry.

Upvotes: 2

Related Questions