每次在做新项目或新功能时会添加新表,这时就要在项目中添加表对应的model,多数时都是自己一个表一个字段的敲。多表了,时间长了总觉得这样操作很繁锁。于是就想微软有没有提供一个命令能把表转成c#model呢?所以就有了下面的方法
因为不想直接操作正式的项目。所以我自己先建一个控制台项目,将表模型生成好后再复制到正式项目中
使用dotnet ef 命令
若报以下错
先执行 dotnet tool install --global dotnet-ef 进行安装
然后执行命令
dotnet ef dbcontext scaffold "Host=172.16.0.10;Database=db_dev;Username=db_app;Password=pwd;Persist Security Info=True" Npgsql.EntityFrameworkCore.PostgreSQL --output-dir model
若报以下错误
则请将盘符定位到项目所在目录中含有xxxx.csproj的那里,如在些目录下执行上面命令
注:项目中必须引用以下nuget包
第三个npgsql是根据自己所用的数据库进行替换
最后执行命令后的结果如下
命令会将指定的数据中的表都转换成c#model
如果大家还有其他更好的方欢迎指教。