Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute insert query using Entity Framework

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

like image 555
Ajay George Avatar asked Jul 10 '15 14:07

Ajay George


People also ask

How do I insert a record into Entity Framework?

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.

How do you create a insert query?

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


2 Answers

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)
);
like image 59
Andzej Maciusovic Avatar answered Oct 19 '22 14:10

Andzej Maciusovic


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);
like image 25
Micke Avatar answered Oct 19 '22 13:10

Micke