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' ?
Insert DataUse the DbSet. Add method to add a new entity to a context (instance of DbContext ), which will insert a new record in the database when you call the SaveChanges() method. In the above example, context. Students.
There are two basic syntax of INSERT INTO statement is as follows: INSERT INTO TABLE_NAME (column1, column2, column3,... columnN)] VALUES (value1, value2, value3,... valueN);
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)
);
Apart from the obvious question why you are writing SQL, it seems you are missing a closing parenthesis, after the third {2}
parameter:
Contex.database.ExecuteSQLCOmmand(@"Insert into tableName Values({0},{1},{2})",param1,param2,param3);
Then it is also a good practise to specify column names, like so:
Contex.database.ExecuteSQLCOmmand(@"Insert into tableName (col1, col2, col3) Values({0},{1},{2})",param1,param2,param3);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With