Executing Insert Statement with Dapper

c# dapper insert-into

Question

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.

Accepted Answer

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.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why