Maf Maf - 1 year ago 796
C# Question

error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation

I've converted some code from vb.net to c# but it's having problems with a lambda.

error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.

Here's the translated code..

dynamic ds = (JArray)o["Tables"][0]["Rows"];
using(var connection = new SqlConnection(cnnString))
{connection.Open();
ds.Select(ja =>
connection.Execute("INSERT INTO dbo.AddPlay(UserId, Timestamp, YoutubeId, Source, PlayCount, Rating) " +
" VALUES(ja(0).Value<string>(), ja(1).Value<string>() ja(2).Value<string>(), ja(3).Value<string>(), GetInt(ja(4)), GetInt(ja(5)))"));
}

Answer Source

Using a foreach and creating a parameterized SqlCommand is best practice

var ds = (JArray)o["Tables"][0]["Rows"];

using (var connection = new SqlConnection(cnnString)) {
    connection.Open();
    var cmdIns = new SqlCommand("INSERT INTO dbo.AddPlay(UserId, Timestamp, YoutubeId, Source, PlayCount, Rating) VALUES(@UserId, @Timestamp, @YoutubeId, @Source, @PlayCount, @Rating)", connection);
    cmdIns.Parameters.Add("@UserId", SqlDbType.VarChar, 20);
    cmdIns.Parameters.Add("@Timestamp", SqlDbType.VarChar, 20);
    cmdIns.Parameters.Add("@YoutubeId", SqlDbType.VarChar, 20);
    cmdIns.Parameters.Add("@Source", SqlDbType.VarChar, 20);
    cmdIns.Parameters.Add("@PlayCount", SqlDbType.Int);
    cmdIns.Parameters.Add("@Rating", SqlDbType.Int);

    foreach (var ja in ds) {
        cmdIns.Parameters["@UserId"].Value = ja(0).Value<string>();
        cmdIns.Parameters["@Timestamp"].Value = ja(1).Value<string>();
        cmdIns.Parameters["@YoutubeId"].Value = ja(2).Value<string>();
        cmdIns.Parameters["@Source"].Value = ja(3).Value<string>();
        cmdIns.Parameters["@PlayCount"].Value = GetInt(ja(4));
        cmdIns.Parameters["@Rating"].Value = GetInt(ja(5));

        cmdIns.ExecuteNonQuery();
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download