Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I add a parameter to entity framework raw sql command

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

        }
like image 804
Rod Avatar asked Aug 08 '13 02:08

Rod


People also ask

How use raw SQL query in Entity Framework Core?

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.

Which of the following executes a raw SQL query in the database using EF core?

Entity Framework Core provides the DbSet. FromSql() method to execute raw SQL queries for the underlying database and get the results as entity objects.


Video Answer


1 Answers

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));
like image 134
Damith Avatar answered Sep 20 '22 07:09

Damith