[英]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.我知道要在 EF 中更新模型,我必须先获取模型,然后再更改它,然后更改 dbContext.SaveChanges() 但有时在我的 Asp.net mvc 项目中,我想更新表中的一个字段,但我不知道它的 ID并且必须使用 where 子句获取它。 but i don't want connect twice to database , because in ADO.net i can write:但我不想两次连接到数据库,因为在 ADO.net 中我可以写:
UPDATE MyTable SET Field3 = "NewValue" WHERE Active = 1
and now i want write a linq to sql for EF that work like that.现在我想为 EF 编写一个 linq 到 sql 那样的工作。 Is exist any way for that?存在任何方式吗? thanks谢谢
You can't.你不能。 EF is ORM, that means, you need to work with separate objects (update them one by one). EF 是 ORM,这意味着,您需要使用单独的对象(一一更新它们)。
Look at EntityFramework.Extended library for that:看看EntityFramework.Extended库:
//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对于 EF Core: EntityFramework-Plus
You can use the raw query function in EF.您可以在 EF 中使用原始查询功能。
var query = "UPDATE MyTable SET Field3 = 'NewValue' WHERE Active = 1";
using (var context = new YourContext())
{
context.Database.ExecuteSqlCommand(query);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.