How to execute insert query using Entity Framework

.net c# entity-framework sql

Question

I am trying to execute a insert query using Entity Framework.

I have something like this:

Context.database.ExecuteSqlCommand("Insert into tableName Values({0},{1},{2}", param1, param2, param3)

but this is throwing an error

incorrect syntax near '@p1'

What is this '@p1' ?

1
2
7/10/2015 3:18:05 PM

Popular Answer

You missing the closing ) at the end of your INSERT.

It should be:

Context.database.ExecuteSqlCommand("Insert into tableName Values({0},{1},{2})", param1, param2, param3)

Alternatively, you could use the SqlParameter class:

Context.Database.ExecuteSqlCommand(
    "Insert into tableName Values(@id, @firstName, @lastName)",
    new SqlParameter("id", id),
    new SqlParameter("firstName", firstName),
    new SqlParameter("lastName", lastName)
);
10
8/15/2016 8:01:22 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow