4

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();
                });
3
  • 1
    You shouldn't need to modify the state yourself. EF will do that for you. Commented Jul 6, 2019 at 23:24
  • Also you dont want to do the save changes inside the loop. It does have some performance hits calling it that way. Do it after the foreach. Commented Jul 6, 2019 at 23:25
  • I tried to call it after the loop and the in the first code snippet .. you can see the error :) Commented Jul 6, 2019 at 23:58

1 Answer 1

7

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.