Gop*_*opi 5 c# entity-framework-core efcore.bulkextensions
我们正在尝试批量更新(EFCore.BulkExtensions)基于主键的表。我们只需要更新Name基于Id而不是Age
模型
public class Student
{
public int Id { get; set; } // Primary Key
public string Name { get; set; }
public int Age { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这是我用来尝试使用主键 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);
Run Code Online (Sandbox Code Playgroud)
我的期望是它会更新为 1Name的行的列Id,但我收到以下错误
The given key 'Id' was not present in the dictionary.
Run Code Online (Sandbox Code Playgroud)
那么我如何批量更新(EFCore.BulkExtensions)基于主键的表。
假设这Id是一个主键 (PK),并且您需要仅Name基于Id而不是进行更新Age。
需要PropertiesToInclude在 内设置属性BulkConfig。注意:不必同时使用PropertiesToIncludeand 。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);
Run Code Online (Sandbox Code Playgroud)