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

我的未来我决定 提交于 2021-02-04 12:41:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!