单独生成实体类,再拷贝到
1、创建ef类库(设定一下命名空间namespace,与开发业务系统项目的一致),同时将项目设为启动项目,安装2个Nuget包,如下所示:
Microsoft.EntityFrameworkCore.Tools
Pomelo.EntityFrameworkCore.MySql
2、生成数据库的实体和ef的DbContext对象,在项目根目录下,用到的是 scaffold-dbcontext 命令;
scaffold-dbcontext -force "server=****;user id=root;password=****;database=****" -provider "pomelo.entityframeworkcore.mysql"
server:数据库地址,user id:账号,password:登录密码
如果是针对单表的更新,加一个-tables 后面是要更新的表名
scaffold-dbcontext -force "server=****;user id=root;password=****;database=****" -provider "pomelo.entityframeworkcore.mysql" -tables "mytablename"
执行完成之后会生成指定的是model ,注意:表必须有主键,才会生成,如果没有主机会报 unable to generate entity type for table “xxxx” 警告,当然实体也不会生成出现的问题:如果有表字段为 datetime类型的,生成的时候会报错 应输入标识符,处理方法:把.()去掉。
3、输出到指定文件目录(Models)下:
scaffold-dbcontext -force "server=****;user id=root;password=****;database=****" -provider "pomelo.entityframeworkcore.mysql" -OutputDir Models
4、加 -f 强制覆盖文件
scaffold-dbcontext -force "server=****;user id=root;password=****;database=****" -provider "pomelo.entityframeworkcore.mysql" -OutputDir Models -f
5、查看反向生成命令帮助:
dotnet ef dbcontext scaffold -h
结果:
Usage: dotnet ef dbcontext scaffold [arguments] [options]
Arguments:
<CONNECTION> The connection string to the database.
<PROVIDER> The provider to use. (E.g. Microsoft.EntityFrameworkCore.SqlServer)
Options:
-d|--data-annotations Use attributes to configure the model (where possible). If omitted, only the fluent API is used.
-c|--context <NAME> The name of the DbContext. Defaults to the database name.
--context-dir <PATH> The directory to put the DbContext file in. Paths are relative to the project directory.
-f|--force Overwrite existing files.
-o|--output-dir <PATH> The directory to put files in. Paths are relative to the project directory.
--schema <SCHEMA_NAME>... The schemas of tables to generate entity types for.
-t|--table <TABLE_NAME>... The tables to generate entity types for.
--use-database-names Use table and column names directly from the database.
--json Show JSON output. Use with --prefix-output to parse programatically.
-n|--namespace <NAMESPACE> The namespace to use. Matches the directory by default.
--context-namespace <NAMESPACE> The namespace of the DbContext class. Matches the directory by default.
--no-onconfiguring Don't generate DbContext.OnConfiguring.
--no-pluralize Don't use the pluralizer.
-p|--project <PROJECT> The project to use. Defaults to the current working directory.
-s|--startup-project <PROJECT> The startup project to use. Defaults to the current working directo