DB first (using PostgreSQL) in .NET 5

1.Create a project under your solution, there is DbFirst.API

2. Install EntityFrameworkCore, Microsoft.EntityFrameworkCore.Design, Microsoft.EntityFrameworkCore.Tools, Npgsql.EntityFrameworkCore.PostgreSQL by NuGet

4. Install dotnet-ef

dotnet tool install --global dotnet-ef

5. Add Models.PostgreSQL file folder, and build your project

6. Generate Entity Models

dotnet ef dbcontext scaffold "Server=10.41.21.45;Database=WZSHR;User ID=WXACCOUNT;Password=WXACCOUNT;" "Npgsql.EntityFrameworkCore.PostgreSQL" -p DbFirst.Api -o Models.PostgreSQL --schema WXACCOUNT -f

 7. Replace the DB connection string, it will get it from appsettings.

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
                // optionsBuilder.UseNpgsql("Server=10.41.21.45;Database=WZSHR;User ID=WXACCOUNT;Password=WXACCOUNT;");
                optionsBuilder.UseNpgsql(AppSettings.Configuration.GetConnectionString("DB"));
            }
        }

   8. Source code: CodeAndDbFirst

猜你喜欢

转载自blog.csdn.net/wish366/article/details/120341111