如何使用实体框架核心更新与普通 SQL 更新查询相同的多条记录列表? [英] How to update a list of multiple records same as normal SQL Update query using entity framework core?
问题描述
通常在 SQL 中我们可以写这个查询 UPDATE users SET isAdult = 1 WHERE age >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(Object实体)在Microsoft.EntityFrameworkCore.DbContext.EntryWithoutDetectChanges[TEntity](TEntity实体)在Microsoft.EntityFrameworkCore.DbContext.Entry[TEntity](TEntity entity)
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();
});
推荐答案
错误是因为列表未定义为 EF 实体.
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 更新查询相同的多条记录列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!