问题
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
回答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
回答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);
}
来源:https://stackoverflow.com/questions/44380770/how-can-i-write-sql-update-query-with-where-clause-in-entity-framework-in-c-shar