【发布时间】:2021-02-23 07:08:59
【问题描述】:
我是 .NetCore 新手,正在关注 .NetCore Web Applicaiton 官方教程,可以查看here。
我正在尝试使用这个包将我的应用程序连接到 MySQL 数据库,MySql.Data.EntityFrameworkCore
我的数据库关系结构如下: 课程、学生和注册。课程和学生都可以有多个注册,而注册记录可以有一个课程和一个学生。
Course -> Enrollment <- Student
课程.cs
public class Course
{
public int CourseID { get; set; }
public string Title { get; set; }
public int Credits { get; set; }
public ICollection<Enrollment> Enrollments { get; set; }
}
学生.cs
public class Student
{
public int StudentID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<Enrollment> Enrollments { get; set; }
}
Enrollment.cs
public class Enrollment
{
public int EnrollmentID { get; set; }
public Grade? Grade { get; set; }
public int CourseID { get; set; }
public int StudentID { get; set; }
public Course Course { get; set; }
public Student Student { get; set; }
}
这是我在 Startup.cs 的 ConfigureServices 方法中配置 dbcontext 的方式
services.AddDbContext<ApplicationDbContext>(options =>
options.UseMySQL(
Configuration.GetConnectionString("DefaultConnection")));
这是我的连接字符串的样子;
"ConnectionStrings": {
"DefaultConnection": "server=localhost;port=3306;uid=root;password=***;database=coremvc"
},
这是我的 ApplicationDbContext:
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
}
备注
每当我运行项目时,我只能看到自动创建的 Student 和 Course 表,但看不到招生表。
当我删除导航属性(例如 ICollection 属性和课程和学生属性)时,它起作用了。那里的所有表都已创建。
大概与定义模型中的关系有关。
提前致谢, 干杯
【问题讨论】:
-
查看以下文章:Configure Many-to-Many Relationships in Entity Framework Core和Configuring Many To Many Relationships in Entity Framework Core,在OnModelCreating方法中,尝试使用Fluent API配置连接表。
标签: c# mysql entity-framework asp.net-core .net-core