【问题标题】:EFCore.BulkExtensions - BulkUpdate using pimarykeyEFCore.BulkExtensions - 使用 pimarykey 批量更新
【发布时间】:2020-05-06 17:49:27
【问题描述】:

我们正在尝试批量更新(EFCore.BulkExtensions)基于主键的表。我们只需要根据Id 更新Name 而不是Age

型号

public class Student 
{
    public int Id { get; set; } // Primary Key
    public string Name { get; set; }
    public int Age { get; set; }
}

这是我用来尝试使用主键 Id 更新学生姓名的代码

List<Student> students = new List<Student>();
students.Add(new Student()
{
    Id = 1,
    Name = "Name 1",
    Age = 25
});

var updateByProperties = new List<string> { nameof(Student.Id) };
var propToExclude = new List<string> { nameof(Student.Id) };
var bulkConfig = new BulkConfig { UpdateByProperties = updateByProperties, PropertiesToExclude = propToExclude };
_dbContext().BulkUpdate(students, bulkConfig);

我的期望是它会更新 Id 为 1 的行的列 Name,但我收到以下错误

The given key 'Id' was not present in the dictionary.

那么我如何 BulkUpdate(EFCore.BulkExtensions) 基于主键的表。

【问题讨论】:

    标签: c# entity-framework-core efcore.bulkextensions


    【解决方案1】:

    假设Id 是一个主键(PK),您只需根据Id 而不是Age 更新Name。

    需要在BulkConfig内设置PropertiesToInclude属性。注意:您不必同时使用PropertiesToInclude 和PropertiesToExclude。 (如果你想包含超过一半的属性,最好使用PropertiesToExclude,但你的情况你只想更改名称,所以我们将使用属性Include)。

    另外,不需要定义UpdateByProperties,因为你想通过Id(也就是PK)来更新数据。 UpdateByProperties 定义用作更新查找的属性。

    所以代码应该是这样的:

    List<Student> students = new List<Student>();
    students.Add(new Student()
    {
        Id = 1,
        Name = "Name 1",
        Age = 25
    });
    
    var propToInclude = new List<string> { nameof(Student.Name) };
    var bulkConfig = new BulkConfig { PropertiesToInclude = propToInclude };
    _dbContext().BulkUpdate(students, bulkConfig);
    

    【讨论】:

      猜你喜欢
      • 2010-09-23
      • 2021-10-24
      • 2021-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多