码迷,mamicode.com
首页 > Web开发 > 详细

Setup Entity Framework Core in ASP.NET Core

时间:2017-07-21 17:14:23      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:tin   hot   tab   rsh   tps   pps   settings   http   start   

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

 

Setup Entity Framework Core in ASP.NET Core

标签:tin   hot   tab   rsh   tps   pps   settings   http   start   

原文地址:http://www.cnblogs.com/liangzi4000/p/7217494.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!