Search code examples
c#sql-serverentity-frameworklinq

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


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


Solution

  • 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