entity framework core 生成 postgresql 数据库实体

时间:2022-05-23 06:05:42

.net core 2.0

使用db first 方式生成 表 和context

PM 控制台运行命令出错

Scaffold-DbContext "Host=localhost;Database=mydatabase;Username=myuser;Password=mypassword" Npgsql.EntityFrameworkCore.PostgreSQL

说找不到什么引用,找半天,有人说用dotnet ef 命令可用

,https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/190

需要使用

EF Core .NET Command-line Tools工具

https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dotnet

需要安装包

Install-Package Microsoft.EntityFrameworkCore.Tool
Install-Package Npgsql.EntityFrameworkCore.PostgreSQL
Install-Package Npgsql.EntityFrameworkCore.PostgreSQL.Design

项目文件 .csprog

需添加配置,DotNetCliToolReference

参考:https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dotnet

 
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup> <ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.2" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="2.0.1" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL.Design" Version="1.1.1" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet"
Version="2.0.2" />
</ItemGroup> </Project>

注意引用的版本号,和本机的不一定一样,要匹配,不懂就装个最新的

Install-Package Microsoft.EntityFrameworkCore.Tools -Version 2.0.2

完成安装配置后,在项目目录执行

dotnet ef dbcontext scaffold "Host=localhost;Database=mydatabase;Username=myuser;Password=mypassword" Npgsql.EntityFrameworkCore.PostgreSQL
生成代码