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

别说谁变了你拦得住时间么 提交于 2019-12-24 19:33:52

问题


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:


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();


来源:https://stackoverflow.com/questions/56918249/how-to-update-a-list-of-multiple-records-same-as-normal-sql-update-query-using-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!