close

今天來到最重要的地方,如何串接資料庫 ! ! 這邊使用 entityframework + sql server。 

會學到:

1.學到了如何下載EF 套件

2.如何設定連線字串

3.並註冊服務到系統(service)。

 

1. 從Nuget下載套件,我這邊已經下載好了,給大家參考。

image

想要知道下載好的套件去哪裡了嗎? (下圖兩個地方都看得到喔)

image

image

2.像系統註冊,我要使用資料庫這個服務

那要在哪邊設定服務呢?? 

在Startup 裡的 ConfigureServices函式裡面設定。

程式碼:

public void ConfigureServices(IServiceCollection services)
{
         services.AddDbContext<ModuleContext>(options =>
              options.UseSqlServer(Configuration.GetConnectionString("LocalConnection")));

         services.AddControllersWithViews();
}

UseSqlServer() : 是連結資料庫這個動作,先連線看看有沒有問題。

Configuration.GetConnectionString("LocalConnection") : 能夠選取到 appsettings.json裡面設定的資料庫連線參數。(如下圖)

image

程式碼:

"ConnectionStrings": {
    "LocalConnection": "Server=(localdb)\\mssqllocaldb;Database=ModuleCore;Trusted_Connection=True;MultipleActiveResultSets=true"
  },

 

這樣第一步的設定就還成囉~

​​​​​​​學到了如何下載EF 套件,如何設定連線字串,並註冊服務到系統。

arrow
arrow

    阿駿 發表在 痞客邦 留言(0) 人氣()