您的位置:首页 > 编程语言 > ASP

Setup Entity Framework Core in ASP.NET Core

2017-07-21 16:04 706 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐