Netcore+Mysql+EF(二) 实体模型生成数据库

烂漫一生 提交于 2020-08-10 05:32:18

1.添加引用

Microsoft.EntityFrameworkCore.Tools

MySql.Data.EntityFrameworkCore

此处我用的是Mysql,其他数据库改成相应的EntityFrameworkCore即可

2.创建实体

根目录下创建Models文件夹

创建实体

    public class User
    {
        [Key]
        public int Id { get; set; }  
        public string Nickname { get; set; }
        public string Tel { get; set; }
        public string Address { get; set; }
        public int Status { get; set; }
    }

// 注:实体类中含Id,会自动识别为[Key],[Key]可省略,若表没有Id则需要设置,不然会报错,如下:

 The entity type 'XXX' requires a primary key to be defined, If you intended to use a keyless entity type call 'HasNoKey()'. 

3.创建Context

根目录下创建Context文件夹,并创建DBContext.cs

    public class DBContext : DbContext
    {
        //必须
        public DBContext() { }
        public DBContext(DbContextOptions<DbContext> options)
            : base(options)
        {
        }


        public DbSet<User> Users { get; set; }
        //必须
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //base.OnConfiguring(optionsBuilder);
            if (!optionsBuilder.IsConfigured)
            {
                 optionsBuilder.UseMySQL("server=localhost;userid=XXX;pwd=XXX;port=3306;database=XXX;sslmode=none");
            }
        }

    }

 

4.配置数据库连接

打开appsetting.json

5.ConfigureService注册服务

6.生成

在生成项目上右击-》在资源文件中打开-》在地址栏输入cmd

dotnet ef migrations add test //test可以随意填写,可填写数据库名或者服务名等

========= 修改版本==========
错误:No project was found. Change the current working directory or use the --project option.
解决办法:dotnet ef migrations add test --project MyApp.Migrations // MyApp.Migrations为程序集名称

如果出现如下错误,可按照第二段代码进行安装,之后再重新执行上面代码。

执行成功如下

生成成功后,项目中多出

更新创建表到数据库,执行(注:此数据库在创建之前是不能存在的,否则会报错,且创建不了

//更新到数据库
dotnet ef database update --project MyApp.Migrations // MyApp.Migrations为程序集名称

运行完成后,数据库中就创建了名字为你在配置的数据库连接语句中的database的数据库,并生成了包含__efmigrationshistory及实体模型的表

 

传送门 Netcore+Mysql+EF(一) 数据库生成实体模型

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!