Entity Framework 6.2 - add children with DbSet.Include() but prevent duplicate children on DbSet.AddRange()

柔情痞子 提交于 2019-12-13 03:37:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!