Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
                });
like image 750
Shady Mohamed Sherif Avatar asked Oct 20 '25 12:10

Shady Mohamed Sherif


1 Answers

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();
like image 123
Tony Abrams Avatar answered Oct 23 '25 08:10

Tony Abrams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!