【问题标题】:How to remove rows for deleted fields from relationship table in entity framework如何从实体框架中的关系表中删除已删除字段的行
【发布时间】:2013-01-01 07:55:38
【问题描述】:

我有StudentCourse,它们之间的关系为StudentCourse。这些类中的字段如下:

public class Student
    {
        public int StudentId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int CourseId { get; set; }
        [ForeignKey("CourseId")]
        public Course Course { get; set; }
    }


public class Course
    {
        public int CourseId { get; set; }
        public string CourseName { get; set; }
    }



public class StudentCourse
    {   
        public int ID { get; set; }
        public virtual Student Student { get; set; }
        public virtual Course Course {get;set;}
    }

当我删除student 表中的学生时,我想从关系StudentClass 中删除相应的行。我该怎么做?

【问题讨论】:

  • @Slauma:你能回答这个问题吗?
  • 模型很奇怪。你不想要StudentCourse 之间的多对多关系吗,即一个学生可以参加许多 个课程,一个课程可以有许多 个学生?通常您不需要StudentCourse 实体,因为EF 会自动管理链接表。你能解释一下为什么Student 只有一个Student.Course 引用而不是课程集合吗?
  • @Slauma 我是实体框架的新手,不知道出了什么问题..

标签: c# entity-framework


【解决方案1】:

我相信您实际上希望 StudentCourse 之间存在多对多关系:一个学生可以参加 许多 课程,而一个课程可以有 许多 em> 学生。

在这种情况下,您可以简化模型:

public class Student
{
    public int StudentId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public ICollection<Course> Courses { get; set; }
}

public class Course
{
    public int CourseId { get; set; }
    public string CourseName { get; set; }
    public ICollection<Student> Students { get; set; }
}

不需要“加入实体”StudentCourse。 EF 将从此模型创建三个表:Students 表、Courses 表和 StudentCourses(或 CourseStudents)表,它们将具有复合主键 (StudentId, CourseId)(或类似名称)。这两个部分都是各自表的外键。

对于数据库中的两个外键关系级联删除默认开启。因此,如果Student 被删除,连接表中的链接记录将被自动删除。 Course 被删除时也是如此。

您还可以显式定义连接表和连接表列的详细名称,也可以只使用单个集合,例如在 Student 中仅使用 Courses 集合,但在 @ 中不使用 Students 集合987654335@。为此,您必须使用 Fluent API:

modelBuilder.Entity<Student>()
    .HasMany(s => s.Courses)
    .WithMany() // no parameter if there is no collection in Course
    .Map(m =>
    {
        m.MapLeftKey("StudentId");
        m.MapRightKey("CourseId");
        m.ToTable("StudentCourses");
    });

【讨论】:

  • 您能否更新答案以提供有关复合外键的详细信息?并且只从一个表中删除而不是从另一个外键表中删除?
  • @BhushanFirake:在这个例子中你不需要关心复合键。 EF 会自动为连接表管理它。只删除Student: context.Students.Remove(student); 它将删除连接表中的学生和相关条目。它不会删除任何课程。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-19
  • 2015-05-06
相关资源
最近更新 更多