How to update a list of multiple records same as normal SQL Update query using entity framework core?

asp.net-core entity-framework-core

Question

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();
                });
1
0
7/13/2019 5:31:51 AM

Accepted Answer

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();
3
7/7/2019 1:32:33 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow