Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 365
AliOsat Mostafavi Avatar asked Jun 06 '17 03:06

AliOsat Mostafavi


People also ask

Can you update a column that you have in your WHERE clause?

To do a conditional update depending on whether the current value of a column matches the condition, you can add a WHERE clause which specifies this. The database will first find rows which match the WHERE clause and then only perform updates on those rows.

Can WHERE clause be used in update DELETE statement?

DELETE Syntax Notice the WHERE clause in the DELETE statement. The WHERE clause specifies which record(s) should be deleted. If you omit the WHERE clause, all records in the table will be deleted!

How do I update items in Entity Framework?

To update this entity we need to attach the Department to the context and inform it to mark its status as Modified . Now if we call the SaveChanges method, the context will send an update query to the database.

Can we use WHERE clause in update statement?

UPDATE Syntax Notice the WHERE clause in the UPDATE statement. The WHERE clause specifies which record(s) that should be updated. If you omit the WHERE clause, all records in the table will be updated!


2 Answers

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

like image 98
Backs Avatar answered Sep 19 '22 17:09

Backs


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); 
}
like image 30
IvanJazz Avatar answered Sep 17 '22 17:09

IvanJazz