How can i write SQL update query with where clause in Entity Framework in C#

16,024

Solution 1

You can't. EF is ORM, that means, you need to work with separate objects (update them one by one).

Look at EntityFramework.Extended library for that:

//update all tasks with status of 1 to status of 2
context.Tasks
    .Where(t => t.StatusId == 1)
    .Update(t => new Task { StatusId = 2 });

For EF Core: EntityFramework-Plus

Solution 2

You can use the raw query function in EF.

var query = "UPDATE MyTable SET Field3 = 'NewValue' WHERE Active = 1";
using (var context = new YourContext()) 
{ 
    context.Database.ExecuteSqlCommand(query); 
}
Share:
16,024
AliOsat Mostafavi
Author by

AliOsat Mostafavi

Updated on June 29, 2022

Comments

  • AliOsat Mostafavi
    AliOsat Mostafavi almost 2 years

    I know that for update a model in EF i must get model then change it then dbContext.SaveChanges() but sometimes in my Asp.net mvc project , i want update a field in my table and i don't know it 's id and must be get it with where clause. but i don't want connect twice to database , because in ADO.net i can write:

    UPDATE MyTable SET Field3 = "NewValue" WHERE Active = 1 
    

    and now i want write a linq to sql for EF that work like that. Is exist any way for that? thanks