I'm doing a bulk insert of an entity with related entities and I need to avoid saving duplicate records. Unfortunately, all entities are getting saved even if they already exist. I'm using the EF extensions library here.
This question is a possible duplicate of this one but its comments have not solved my problem.
Below is my bulkInsert code:
await _context.BulkInsertAsync(Registrations, options: o =>
{
o.IncludeGraph = true;
o.IncludeGraphOperationBuilder = operation =>
{
switch (operation)
{
case BulkOperation<School> School:
School.InsertIfNotExists = true;
School.ColumnPrimaryKeyExpression = c => new { c.SchoolId, c.SchoolIdentifier };
School.AllowDuplicateKeys = false;
break;
case BulkOperation<Student> Student:
Student.InsertIfNotExists = true;
Student.ColumnPrimaryKeyExpression = c => new{c.StudentId, c.StudentIdentifier};
Student.AllowDuplicateKeys = false;
break;
case BulkOperation<Registration> Registration:
Registration.InsertIfNotExists = true;
Registration.ColumnPrimaryKeyExpression = m => new { m.SchoolId, m.StudentId };
Registration.AllowDuplicateKeys = false;
break;
}
};
});
And the entity definitions:
public class Registration
{
[Key]
public int RegistrationId { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public int StudentId { get; set; }
public Student Student { get; set; }
public int SchoolId { get; set; }
public School School { get; set; }
}
public class School
{
[Key]
public int SchoolId { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public int SchoolIdentifier { get; set; }
}
public class Student
{
[Key]
public int StudentId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string StudentIdentifier { get; set; }
}