[英]How to execute insert query using Entity Framework
I am trying to execute a insert query using Entity Framework. 我正在尝试使用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'
'@ p1'附近的语法不正确
What is this '@p1' ? 这是什么'@ p1'?
You missing the closing ) at the end of your INSERT. 您在INSERT结束时错过了结束。
It should be: 它应该是:
Context.database.ExecuteSqlCommand("Insert into tableName Values({0},{1},{2})", param1, param2, param3)
Alternatively, you could use the SqlParameter class: 或者,您可以使用SqlParameter类:
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: 除了显而易见的问题,为什么要编写SQL,在第三个
{2}
参数之后,似乎缺少一个右括号:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.