【问题标题】:EntityFrameworkCore with MySql not creating all tables带有 MySql 的 EntityFrameworkCore 未创建所有表
【发布时间】: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 属性和课程和学生属性)时,它起作用了。那里的所有表都已创建。

大概与定义模型中的关系有关。

提前致谢, 干杯

【问题讨论】:

标签: c# mysql entity-framework asp.net-core .net-core


【解决方案1】:

如果你想使用 MySQL,你应该使用 fluent API。搜索它。

【讨论】:

  • 谢谢,我会调查的。
【解决方案2】:

也许这会有所帮助:https://dev.mysql.com/doc/connector-net/en/connector-net-entityframework-core-example.html

参见步骤 2.b 方法 OnModelCreating

您所遵循的教程适用于 MSSQL,并且您使用的是 MySQL。

【讨论】:

    猜你喜欢
    • 2017-07-12
    • 2022-07-26
    • 2019-10-12
    • 2016-07-29
    • 2010-11-08
    • 2020-09-01
    • 2014-03-03
    • 2021-08-05
    • 1970-01-01
    相关资源
    最近更新 更多