如何使用实体框架核心更新与常规SQL Update查询相同的多个记录的列表? [英] How to update a list of multiple records same as normal SQL Update query using entity framework core?
问题描述
通常在SQL中,我们可以编写此查询 UPDATE用户SET isAdult = 1年龄> 18
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();
错误是
System.InvalidOperationException:找不到实体类型列表
。确保已将实体类型添加到模型中。 Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.GetOrCreateEntry(对象
实体,位于
)Microsoft.EntityFrameworkCore.DbContext.EntryWithoutDetectChanges [TEntity](TEntity
实体),位于
。 EntityFrameworkCore.DbContext.Entry [TEntity](TEntity实体)
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();
这篇关于如何使用实体框架核心更新与常规SQL Update查询相同的多个记录的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!