【问题标题】:how to check many to many table for duplicates thru Entity Framework如何通过实体框架检查多对多表的重复项
【发布时间】:2013-11-20 22:58:07
【问题描述】:

例如,采用以下数据库表:学生、课程和学生课程。

在 Entity Framework 中,如何确保在为学生添加新课程时,该课程不存在?这对我来说意味着检查 StudentCourses 表。

我需要直接写 sql 来检查吗?

【问题讨论】:

  • 你的意思是StudentsCourses.Where(x => x.StudentId == studentId && x.CourseId == courseId) ??
  • 但是学生课程在导航属性中不可用。
  • 那么你实例化上下文然后查询上下文,按照下面的答案!

标签: c# entity-framework


【解决方案1】:
using (var context = new StudentContext()
{
 var alreadyExists = context.StudentsCourses.Any(x => x.StudentId == studentId && x.CourseId == courseId);
}

【讨论】:

  • 我确实实例化了数据上下文 MyDBEntities 对象,但没有可以查询的 StudentsCourses 对象。我在这方面很新,所以我可能会误解,道歉。我可以对学生进行操作,也可以对课程进行操作。
  • 您是先将 StudentsCourses 表添加到设计器中还是通过代码添加,还是根本不添加?你需要这张桌子。
  • 我使用数据库来创建设计器(不是代码优先)。默认情况下,它仅在设计器上显示学生和课程。如果我点击链接,它会显示他们通过 StudentCourses 连接,但该表没有显示。
【解决方案2】:

如果您有简单的多对多关系,您可能没有StudentsCourse 实体。我喜欢这种添加多对多关系的模式:

public Student
{
   private _Courses = new List<Course>();

   public int ID { get; set; }

   public virtual ICollection Courses 
   {
      get { return _Courses; }
      protected set { _Courses = value; }
   }

   public void AddCourse(Course course)
   {
      //And you can add your duplicate check here
      if(!Courses.Any(c => c.ID == course.ID))
         Courses.Add(course);
   }
}

不幸的是,Courses 属性不是只读集合,因此它不会阻止有人在其他地方绕过该方法:

student.Courses.Add(course);

但是其他答案中建议的方法也不能阻止

【讨论】:

    【解决方案3】:

    创建一个方法:

    public bool IsStudentOnCourse(int studentId, int courseId)
    {
        using (var db = new DBContext()) //replace for real context..
        {
            return db.StudentsCourses.Any(x => x.StudentId == studentId && x.CourseId == courseId);
        }
    }
    

    【讨论】:

    • 将我的评论转换为答案。
    【解决方案4】:

    BenjaminPaul 的回答非常有效。另一种选择是尝试检索您的学生,如果不存在,则创建一个新的。

    你可以创建一个这样的方法

    public StudentCourse CreateOrUpdate(VM_StudentCourse studentCourse)
    {
        StudentCourse dbStudentCourse;
        using (var context = new StudentContext()
        {
            dbStudentCourse = context.StudentsCourses.FirstOrDefault(x => x.StudentId == studentCourse.studentId && x.CourseId == studentCourse.courseId);
            If (dbStudentCourse == null)
            {
               dbStudent = new StudentCourse();
               dbStudent.StudentId = studentCourse.StudentId;
               dbStudent.CourseId = studentCourse.CourseId;
               context.Add(dbStudent);
            }
            dbStudent.OtherProperty1 = studentCourse.SomeProp;
            dbStudent.OtherProperty2 = studentCourse.SomeOtherProp;
    
            context.SaveChanges();
        }
        return dbStudentCourse;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-20
      • 1970-01-01
      • 1970-01-01
      • 2012-05-28
      • 1970-01-01
      • 2011-11-13
      • 2014-08-18
      相关资源
      最近更新 更多