EFCore.BulkExtensions - 利用主键进行批量更新

5
我们正在尝试使用主键批量更新表格 (EFCore.BulkExtensions)。我们需要基于 Id 而不是 Age 来仅更新 Name
模型:
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.

那么我如何基于主键使用EFCore.BulkExtensions批量更新数据表呢?

1个回答

5
假设Id是一个主键(PK),您需要仅基于Id更新Name,而不是Age
BulkConfig内设置PropertiesToInclude属性。注意:您不必同时使用PropertiesToIncludePropertiesToExclude。(如果要包含超过一半的属性,则最好使用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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接