EFCore.BulkExtensions - BulkUpdate using pimarykey

2.7k views Asked by At

We are trying to BulkUpdate(EFCore.BulkExtensions) a table based on primary key. We need to update ONLY Name based on Id and not Age

Model

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

Here is the code I used to try to update a student's name using primary key 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);

My expectation here is it will update column Name of a row which has Id as 1 but I am getting the following error

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

So how do I BulkUpdate(EFCore.BulkExtensions) a table based on primary key.

1

There are 1 answers

0
Lkor On

Let's suppose that Id is a primary key (PK) and you need to update ONLY Name based on Id and not Age.

It is needed to set PropertiesToInclude attribute within BulkConfig. Attention: you do not have to use PropertiesToInclude and PropertiesToExclude at the same time. (If you want to include more than half attributes, it is better to use PropertiesToExclude, but in your case you want to change only Name, so we will use the attribute Include).

Also, it is not needed to define UpdateByProperties, because you want to update data by Id (which is PK). UpdateByProperties define attributes which are used as lookup for updating.

So the code should be like that:

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);