在 EF Core 中设计多对多关系

问题描述 投票:0回答:1

你好 我有一个问题。 如果我们想要有两个表(Departmentsubject),这两个表之间具有多对多关系 好吧,如果我们想在Subject表中添加一门可能在一个或多个系教授的科目。我们如何设计它的表格?

这是我的代码:

public class Department 
 { 
    public int Id { get; set; } public string Name { get; set; } 
    public List<SubjectDepartment> SubmDepartmentsList { get; set;   } 
}


public class Subject 
{ 
  public int Id { get; set; } 
  public string Name { get; set; } 
  public int FacultyId { get; set; } public int DepartmetnId { get; set;} 
  public List<SubjectDepartment> SubjectDepartmentsList { get; set; }
 } 


public class SubjectDepartment
{
    public int DepartmentId { get; set; }
    public Department Department { get; set; }
    public int SubjectId { get; set; }
    public Subject subject { get; set; }
}


 public class DepartmentMapping : IEntityTypeConfiguration<Department>
 {
        public void Configure(EntityTypeBuilder<Department> builder) { builder.HasKey(x => x.Id); }
 }

public class SubjecMapping : IEntityTypeConfiguration<Subject>
{
    public void Configure(EntityTypeBuilder<Subject> builder) { builder.HasKey(x => x.Id); }
}

public class SubjectDeparmentMapping : IEntityTypeConfiguration<SubjectDepartment>
{
    public void Configure(EntityTypeBuilder<SubjectDepartment> builder) { builder.HasKey(x => new { x.DepartmentId, x.SubjectId }); builder.HasOne(x => x.Department).WithMany(x => x.SubmDepartmentsList).HasForeignKey(x => x.DepartmentId); builder.HasOne(x => x.subject).WithMany(x => x.SubjectDepartmentsList).HasForeignKey(x => x.SubjectId); }
}

搜索并红色微软文档

c# entity-framework asp.net-core
1个回答
0
投票
  • 假设您已经创建了一个主题(id:1,名称:Subject1)并且已经创建了一个部门部门(id:1,名称:Departement1)

    context.SubjectDepartments.Add(new SubjectDepartment{DepartmentId = 1,SubjectId=1  };
    context.SaveChanges();
    
  • 假设您已经创建了一个主题(id:1,名称:Subject1)和一个尚未创建的部门部门(名称:“新部门”)

     var subjectDepartment= new SubjectDepartment{SubjectId=1,Departement = new Departement {Name ="new departement"}};
    context.SubjectDepartments.Add(subjectDepartment);
    context.SaveChanges();
    
  • 假设您有一个新主题(名称:新主题)和一个已创建的部门部门(id:1,名称:Departement1)

    var subjectDepartment= new SubjectDepartment{Subject= new Subject{Name="new subject"} ,DepartementId=1};
    context.SubjectDepartments.Add(subjectDepartment);
    context.SaveChanges();
    
© www.soinside.com 2019 - 2024. All rights reserved.