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

c# entity-framework

Question

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

        }
1
12
8/8/2013 2:31:21 AM

Accepted Answer

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));
25
6/13/2016 7:27:00 PM

Popular Answer

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow