实体框架6.2

编程入门 行业动态 更新时间:2024-10-09 00:46:04
本文介绍了实体框架6.2-使用DbSet.Include()添加子项,但防止DbSet.AddRange()上的子项重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我知道在将实体从一个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

本文发布于:2023-11-15 06:26:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1591953.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实体   框架

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!