9

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' ?

4
  • 5
    why are you writing SQL in entity framework to do an insert? Commented Jul 10, 2015 at 14:05
  • @DLeh yes I agree, I would use Sql Command only to execute stored procedures Commented Jul 10, 2015 at 14:14
  • i need to do something as dynamic insertion to tables where destination table might change. And they need entity framework. And they has said to use dynamic insertion queries Commented Jul 10, 2015 at 14:15
  • @p1 is the name of the first parameter in the sql script generated by EF. Commented Jul 27, 2021 at 14:35

2 Answers 2

17

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)
);
Sign up to request clarification or add additional context in comments.

Comments

4

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.