How would I add a parameter to following Entity Framework raw SQL command? For example, what if I wanted to make the Id
a parameter?
using (var context = new NorthwindDBEntities())
{
context.Database.ExecuteSqlCommand(@"
UPDATE dbo.Customers
SET Name = 'Test' WHERE Id = 1
");
}
context.Database.ExecuteSqlCommand(@"UPDATE dbo.Customers
SET Name = 'Test' WHERE Id = @Id", new SqlParameter("Id", 1));
in case of multiple parameters
context.Database.ExecuteSqlCommand(@"UPDATE dbo.Customers
SET Name = 'Test' WHERE Id = @id and Name =@name",
new SqlParameter("Id", id),
new SqlParameter("name", fname));
The following code should work for this scenario:
using (var context = new NorthwindDBEntities())
{
context.Database.ExecuteSqlCommand(@"
UPDATE dbo.Customers
SET Name = 'Test' WHERE Id = {0}
", 1);
}
You can also use SqlParameter
and use @id:
using (var context = new NorthwindDBEntities())
{
context.Database.ExecuteSqlCommand(@"
UPDATE dbo.Customers
SET Name = 'Test' WHERE Id = @id
", new SqlParameter("id", 1));
}