实体框架6.2-使用DbSet.Include()添加子项,但防止DbSet.AddRange()上的子项重复 [英] Entity Framework 6.2 - add children with DbSet.Include() but prevent duplicate children on DbSet.AddRange()

查看:364
本文介绍了实体框架6.2-使用DbSet.Include()添加子项,但防止DbSet.AddRange()上的子项重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在将实体从一个DbContext复制到另一个DbContext时如何防止重复,我的问题是关于其子代的.

我有两个上下文:DbContextHDDDbContextUSB,它们都包含一个"Math" Course.

I have two contexts: DbContextHDD and DbContextUSB and they both contain a "Math" Course.

DbContextHDD还包含:

  • 历史记录" Course.
  • 参加"Math" CourseStudent"Simon".
  • 参加历史记录" CourseStudent杰克".
  • 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-使用DbSet.Include()添加子项,但防止DbSet.AddRange()上的子项重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆