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.
Let's suppose that
Idis a primary key (PK) and you need to update ONLYNamebased onIdand notAge.It is needed to set
PropertiesToIncludeattribute withinBulkConfig. Attention: you do not have to usePropertiesToIncludeandPropertiesToExcludeat the same time. (If you want to include more than half attributes, it is better to usePropertiesToExclude, 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 byId(which is PK).UpdateByPropertiesdefine attributes which are used as lookup for updating.So the code should be like that: