Setup Entity Framework Core in ASP.NET Core

时间:2022-04-07 08:09:14

1. Run following command to install required packages:

Install-Package Microsoft.EntityFrameworkCore.SqlServer

2. For database first approach, need to run below two commands to install required tools:

Install-Package Microsoft.EntityFrameworkCore.Tools

Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design

3. Run following command to generate data models:

Scaffold-DbContext "Server=(local);Database=DBName;User ID=sa;Password=password;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Force -DataAnnotations -Context "CustomDBContext"

4. Move the connection string to config file:

1) Add connection string in file appsettings.json

{
  "ConnectionStrings": {
    "CustomDBContext": "Server=(local);Database=DBName;User ID=sa;Password=password;"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }

2) Define static DBConnectionString property in DBContext file:

    public partial class CustomDBContext : DbContext
    {
        ...
        public static string DBConnectionString { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(DBConnectionString);
        }
        ...
    }

3) Get database connection string from appsettings.json file and assign it to DBConnectionString in Startup.cs file

        public void ConfigureServices(IServiceCollection services)
        {
            // Config database connection string
            NUHOTRSContext.DBConnectionString = Configuration.GetConnectionString("CustomDBContext");
            ...
        }

 

参考链接:

https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db

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

https://joonasw.net/view/asp-net-core-1-configuration-deep-dive