【发布时间】:2021-12-17 21:58:08
【问题描述】:
我正在创建一个 ASP.NET Web API 项目(首先是数据库),它从 MSSQL 数据库中提取数据(只读访问)。数据库有几个表,但没有主键/辅助键(我们无法更改)。我已经建立了一对多关系,没有任何问题,但是当涉及到多对多时,我不得不使用链接表来保存双方的键。
public class Student
{
public int StudentId { get; set; }
public string Name { get; set; }
public IList<StudentCourse> StudentCourses { get; set; }
}
public class Course
{
public int CourseId { get; set; }
public string CourseName { get; set; }
public string Description { get; set; }
public IList<StudentCourse> StudentCourses { get; set; }
}
链接表:
public class StudentCourse
{
public int StudentId { get; set; }
public Student Student { get; set; }
public int CourseId { get; set; }
public Course Course { get; set; }
}
由于数据库中不存在链接表,我收到“Data.SqlClient.SqlException: 'Invalid object name 'StudentCourse'”错误。
public class SchoolContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=.\\SQLEXPRESS;Database=EFCore-SchoolDB;Trusted_Connection=True");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<StudentCourse>().HasKey(sc => new { sc.StudentId, sc.CourseId });
}
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
public DbSet<StudentCourse> StudentCourses { get; set; }
关系:
modelBuilder.Entity<StudentCourse>().HasKey(sc => new { sc.SId, sc.CId });
modelBuilder.Entity<StudentCourse>()
.HasOne<Student>(sc => sc.Student)
.WithMany(s => s.StudentCourses)
.HasForeignKey(sc => sc.SId);
modelBuilder.Entity<StudentCourse>()
.HasOne<Course>(sc => sc.Course)
.WithMany(s => s.StudentCourses)
.HasForeignKey(sc => sc.CId);
我考虑过在这些键上连接表,但它似乎不是处理关系和获取相关记录的有效方法。你会建议什么变通方法?
【问题讨论】:
-
“我考虑在这些键上连接表” 哪些键?你如何加入/链接一些没有在某处有一些共同列的东西?显示现有表的相关列可能有助于了解您想要实现的目标以及它是否可能(EF Core 通常不能容忍不正确的数据库设计)。
-
我已将我的 DbContext 添加到问题中,这正是我的问题,但我尝试使用替代名称来描述它。
-
上下文并不那么有趣,因为它显示了您如何尝试将类映射到......不确定是什么。在您所说的 OP 中,您正在使用无法更改的现有数据库,并且也没有链接表。所以我问您是否可以显示现有的 tables 及其相关的 columns。
-
您的 DbContext 似乎定义了 StudentCourse 表的存在,但您说它在实际数据库中不存在。那么实际的数据库如何确定学生和课程之间的关系?你能告诉我们实际数据库的结构吗?
-
这就是问题所在,我在 db 中没有那个表,我想在这种情况下我不能把它放在 DBContext 中。应用程序是使用数据库优先的方法创建的,但是我们意识到我们必须添加一些东西,例如关系,就一对多而言,大小写相同,我没有在数据库中定义键,而是在 DBContext我已经写过这些表有键(并且没有迁移)。我搜索了一些资源,表明我们可以使用这种方法,因为应用程序使用 db 进行只读。
标签: c# asp.net entity-framework entity-framework-core many-to-many