[C#] .Net Core MVC 連接現有資料庫

  • 7557
  • 0
  • 2018-08-28

從新增專案到Entity Framework Core 2.0連接資料庫(Database first, not code first)
其實Microsoft文件就夠詳細了...囧
做個筆記囉~

需求:Visual Studio 2017 15.3 以上!
舊版請自己更新.Net Core 2.0 

1.先建立好專案及資料庫後
在Tools –> NuGet Package Manager –> Package Manager Console
把套件管理主控台打開唄~
先下載所需套件,嚇command: Install-Package Microsoft.EntityFrameworkCore.SqlServer
因為新增的地方沒有.Net Core EntityFramework的dbContext產生器
所以就只好輸入指令建立DbContext了:

Scaffold-DbContext "Server=127.0.0.1\SQLEXPRESS; Database=資料庫名稱; 
Trusted_Connection=True; User ID=帳號;Password=密碼;"
 Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

server、db名稱、帳號、密碼記得改唷~
參考資料:https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db

2.建立好DB後
會自動產生MyDBContext.cs的檔案,註解掉OnConfiguring()
官方建議移來appsettings.json (官方說明→ an environment variable, the user secret store, or another configuration source)
在ConnectionStrings會在Startup.cs的ConfigureServices中增加

using ProjectName.Models

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddDbContext<MyDBContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("MyDB"))); //將原本ConnectString移到appsettings.json
}

在appsettings.json輸入

"ConnectionStrings": {
    "MyDB": "Server=127.0.0.1\\SQLEXPRESS;Database=資料庫名稱;Persist Security Info=True;User ID=帳號;Password=密碼;"
}

當然全部都在Startup.cs也可以

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    var connection = @"Server=127.0.0.1\SQLEXPRESS;Database=MyDB;Persist Security Info=True;User ID=LionKing;Password=hakunamatata";
    services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection));
}

彈性很高的,說是少了加密儲存吧~

3.在Controller中開始使用
右鍵→新增控制器「使用Entity Framework執行檢視的MVC控制器」
資料內容選擇剛建立的DbContext確定後,會發現Controller多了這幾行:

//20180126 @Huan Add a class variable for the database context immediately after the opening curly brace for the class, and get and instance of the context from ASP.NET Core DI:
//               https://msdn.microsoft.com/zh-tw/magazine/mt703433.aspx

private readonly MyDBContext _context;

public HomeController(MyDBContext context)
{
    _context = context;
}

微軟預設所有呼叫此Controller時,都會先進入與Controller同名的方法執行,並在此連接DB
所以不管呼叫哪個Action,都會先抓DB後再導向至目標Action
其他Action調用_context進行CRUD
記得要檢查上面有沒有using
 

using System.Linq;
using Microsoft.EntityFrameworkCore;


當然原本習慣的寫法,可直接在類別底下一開始的地方先放

MyDBContext db = new MyDBContext();

兩種方法都可行,看喜歡哪個囉~

更新到新版.net core後會發生錯誤:ArgumentException: AddDbContext was called with configuration, but the context type 'WeatherContext' only declares a parameterless constructor.
理由是需要加一段宣告在DBContext.cs,讓DBcontext進行初始化

public WeatherContext(DbContextOptions<WeatherContext> options) : base(options)
{

}

 

============================分隔線==============================

1. 如果資料庫有更新,需要刷新Model資料夾

只要在建立DB的指令後加上-f (-force)強制覆蓋即可

Scaffold-DbContext "Server=127.0.0.1\SQLEXPRESS; Database=MyDB; 
Trusted_Connection=True; User ID=LionKing;Password=hakunamatata;"
 Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -force

2. 專案要沒有錯誤才能執行指令,不然會直接顯示「Build Failed.」然後就結束了...