【问题标题】:Bulk updates using linq entities使用 linq 实体进行批量更新
【发布时间】:2015-06-25 11:52:34
【问题描述】:

我有一个对象列表,例如 列表 类别有属性,CategoryId,CategoryName,Categorymessage,

我必须使用这个列表来更新数据库表中的记录 类别,具有相同的列 CategoryId、CategoryName、CategoryMessage 对于列表中与数据库表中具有匹配 CategoryId 的项目

如何使用实体框架扩展进行批量更新, 我看到的示例具有如下硬编码的更新值(statusId = 2), 而对我来说,必须从列表中与数据库表中的 categoryId 匹配的项目中检索该值。

 context.Tasks.Update(
t => t.StatusId == 1, 
t => new Task {StatusId = 2});

提前致谢。

【问题讨论】:

    标签: linq updates entities bulk


    【解决方案1】:

    我不确定这是否是您要找的?我没有运行这段代码。

     List<Category> categoryList = new List<Category> {
                            new Category { Id = 1, Message = "A", Name = "A"},
                            new Category { Id = 2, Message = "B", Name = "B"},
                            new Category { Id = 3, Message = "C", Name = "C"},
                            new Category { Id = 4, Message = "D", Name = "D"},
                    };
            using (var container = new Model1Container())
            {
               IQueryable<Category> categoryQueryable = container.Categories.Where(x => categoryList.Any(t => t.Id == x.Id));
               foreach (Category item in categoryQueryable)
               {
                   var categorySource = categoryList.Where(x => x.Id == item.Id).Select(m => m).FirstOrDefault();
                   item.Message = categorySource.Message;
                   item.Name = categorySource.Message;
               }
    
                    container.SaveChanges();
            }
    

    【讨论】:

    • 谢谢,这就是我要找的,但是这个解决方案是一次更新一条记录,我有多个表有多个记录,所以这个方法效率不高。
    猜你喜欢
    • 2014-07-12
    • 1970-01-01
    • 1970-01-01
    • 2017-10-06
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-22
    相关资源
    最近更新 更多