我知道在将实体从一个DbContext复制到另一个DbContext时如何防止重复,我的问题是关于其子代的.
我有两个上下文:DbContextHDD和DbContextUSB,它们都包含一个"Math" Course.
I have two contexts: DbContextHDD and DbContextUSB and they both contain a "Math" Course.
DbContextHDD还包含:
- 历史记录" Course.
- 参加"Math" Course的Student"Simon".
- 参加历史记录" Course的Student杰克".
- a "History" Course.
- a Student "Simon" who attends "Math" Course.
- a Student "Jack" who attends "History" Course.
我想将所有Student实体从DbContextHDD复制到DbContextUSB,并且还包括DbContextUSB中不存在的所有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();这还会将数学"和历史记录" Course实体从DbContextHDD复制到DbContextUSB.
This also copies "Math" and "History" Course entities from DbContextHDD to DbContextUSB.
在Students.AddRange之后,我在DbContextUSB.Courses.Local中有两个数学" Course实体,它们都具有相同的CourseId,并且SaveChanges都失败了,并显示SQLiteException: UNIQUE constraint failed.
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.
我正在使用代码优先"方法.代理创建被禁用:
I am using the Code-First approach. Proxy creation is disabled:
Configuration.ProxyCreationEnabled = false;我有很多关系:
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; } }推荐答案
您是否尝试过应用过滤器?
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);更多推荐
实体框架6.2
发布评论