Normally in SQL we can write this query UPDATE users SET isAdult = 1 WHERE age >18
I want to apply some edit to all rows that satisfy some condition in entity framework core.
I wrote this code and I got an error
List<User> usersList = _context.Users.Where(u => u.age >18).ToList();
usersList.ForEach(a =>
{
a.isAdult = 1;
});
_context.Entry(usersList).State = EntityState.Modified;
_context.SaveChanges();
The error is
System.InvalidOperationException: The entity type 'List' was not found. Ensure that the entity type has been added to the model. at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.GetOrCreateEntry(Object entity) at Microsoft.EntityFrameworkCore.DbContext.EntryWithoutDetectChanges[TEntity](TEntity entity) at Microsoft.EntityFrameworkCore.DbContext.Entry[TEntity](TEntity entity)
I made this update but I want to know if this is the best way.
List<Users> usersList = _context.Users.Where(u => u.age >18).ToList();
usersList.ForEach(a =>
{
a.isAdult = 1;
_context.Entry(a).State = EntityState.Modified;
_context.SaveChanges();
});
The error was because the list isn't defined as an EF Entity.
In the end, you don't need to modify the state youself.
List<User> usersList = _context.Users.Where(u => u.age >18).ToList();
usersList.ForEach(a => { a.isAdult = 1; });
_context.SaveChanges();