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
");
}
Entity Framework Core allows you to drop down to raw SQL queries when working with a relational database. Raw SQL queries are useful if the query you want can't be expressed using LINQ. Raw SQL queries are also used if using a LINQ query is resulting in an inefficient SQL query.
Entity Framework Core provides the DbSet. FromSql() method to execute raw SQL queries for the underlying database and get the results as entity objects.
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));
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