c# - 实体框架 Remove、RemoveRange 和 EntityState Deleted
问题描述
这三行有什么区别
var courses = _context.Courses
.Include("AssignedCustomers")
.Include("PricingSchedule")
.Include("Licenses")
.Include("GroupCourses")
.Include("GroupLicenses")
.Where(e => courseIds.Contains(e.Id)).ToList();
courses.ForEach(currentCourse =>
{
第一的
_context.CustomerCourses.RemoveRange(currentCourse.AssignedCustomers);
第二
currentCourse.AssignedCustomers.ToList().ForEach(ac =>
{
_context.Entry(ac).State = EntityState.Deleted;
});
第三
currentCourse.AssignedCustomers.ToList().ForEach(ac =>
{
currentCourse.AssignedCustomers.Remove(ac);
});
}
何时使用什么以及在哪种情况下使用?我总是坚持确定应该使用哪一个。我尝试所有对我有用的方法,我保留它。但老实说,我不明白这里的概念
解决方案
Remove Range() 方法用于删除实体框架内的集合或列表。这是使用循环遍历集合并将对象的实体状态设置为已删除的更好选择。
IList<Book> booksToRemove = new List<Book>() {
new Book() { BookId = 1, BookName = "Rich Dad Poor Dad" };
new Book() { BookId = 2, BookName = "The Great Gatsby" };
new Book() { BookId = 3, BooktName = "The Kite Runner" };
};
using (var context = new LibraryDBEntities()) {
context.Books.RemoveRange(booksToRemove);
context.SaveChanges(); }
在上面的示例中,RemoveRange(booksToRemove) 将列表“booksToRemove”的所有实体的状态设置为已删除,并对 context.SaveChanges() 上的所有实体执行 DELETE 命令。
RemoveRange 是一种替代方法,您可以使用它代替上面发布的第二个和第三个选项。建议使用 RemoveRange 和 AddRange 使用实体框架删除和插入大量记录。
推荐阅读
- vim - 基于操作系统映射vim键?
- node.js - 在节点中顺序执行
- node.js - AWS Lambda 函数跳过代码\日志丢失
- algorithm - 我的 Gauss-Jordan 消除有什么问题?
- youtube-iframe-api - 检测 youtube iframe 自动播放失败
- c++ - =删除用户定义的成员函数,除了构造函数,赋值运算符c ++ 11
- stripe-payments - 我在哪里使用 Stripe 付款指定产品?
- php - 将嵌套的 PHP JSON 对象转换为 PHP 数组
- ruby-on-rails - ArgumentError(Api::V1 的副本已从模块树中删除,但仍处于活动状态!)
- sdn - OpenFlow 13,RYU SDN 控制器,buffer_id 到底是什么?