Setup Entity Framework Core in ASP.NET Core

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

 

转载于:https://www.cnblogs.com/liangzi4000/p/7217494.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值