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
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.
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!
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.
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!
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
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With