如何在C#中使用Entity Framework中的where子句编写SQL更新查询 [英] How can i write SQL update query with where clause in Entity Framework in C#

查看:83
本文介绍了如何在C#中使用Entity Framework中的where子句编写SQL更新查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道要在EF中更新模型,我必须先获取模型,然后再对其进行更改,然后更改dbContext.SaveChanges()但是有时在我的Asp.net mvc项目中,我想更新表中的字段,但我不知道它的ID,必须使用where子句来获取它.但是我不想两次连接到数据库,因为在ADO.net中我可以写:

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 

现在我想为EF编写一个linq到sql,就像那样工作.有没有办法做到这一点?谢谢

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

推荐答案

您不能.EF是ORM,这意味着您需要使用单独的对象(一个一个地更新它们).

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

请查看 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 });

对于EF Core: EntityFramework-Plus

For EF Core: EntityFramework-Plus

这篇关于如何在C#中使用Entity Framework中的where子句编写SQL更新查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆