问题
EDIT:
I know how to prevent duplicates when copying entities from one DbContext to another, my question is about their children.
I have two contexts: DbContextHDD
and DbContextUSB
and they both contain a "Math" Course
.
DbContextHDD
also contains:
- a "History"
Course
. - a
Student
"Simon" who attends "Math"Course
. - a
Student
"Jack" who attends "History"Course
.
I would like to copy all Student
entities from DbContextHDD
to DbContextUSB
and also include any Course
entities not already present in DbContextUSB
:
var students = DbContextHDD.Students.Include(s => s.Courses).ToList();
DbContextUSB.Students.AddRange(students);
DbContextUSB.SaveChanges();
This also copies "Math" and "History" Course
entities from DbContextHDD
to DbContextUSB
.
After Students.AddRange
I have two "Math" Course
entities in DbContextUSB.Courses.Local
, both with the same CourseId
and SaveChanges
fails with SQLiteException: UNIQUE constraint failed
.
How can I avoid that?
I am using the Code-First approach. Proxy creation is disabled:
Configuration.ProxyCreationEnabled = false;
I have a many to many relationship:
public class Student
{
public Student()
{
this.Courses = new HashSet<Course>();
}
public int StudentId { get; set; }
[Required]
public string StudentName { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
public class Course
{
public Course()
{
this.Students = new HashSet<Student>();
}
public int CourseId { get; set; }
public string CourseName { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
回答1:
Have you tried to apply a filter?
var targetStudentIds = DbContextUSB.Students.Select(s => s.StudentId).ToArray();
var sourceStudents = DbContextHDD.Students.Include(s => s.Courses).Where(s => !targetStudentIds.Contains(s.StudentId)).ToArray();
DbContextUSB.Students.AddRange(sourceStudents);
来源:https://stackoverflow.com/questions/57872208/entity-framework-6-2-add-children-with-dbset-include-but-prevent-duplicate-c