今天會介紹怎麼在 ASP.NET Core MVC 專案使用 EF Core。 會以現有資料庫當範例。

首先,我已經先建立好了一個 Sample Database ,且只有 Person 一個資料表。 如下圖。

sample-databasesample-database

有資料庫後,我們就要使用反向工程,把資料庫轉成 DbContext。 而 Entity Framework Core tools reference - .NET CLI 有提供 Scaffold 的工具可以讓我們使用。

Scaffold 資料庫

有兩種方式可以 Scaffold 資料庫

  • 使用 dotnet cli

    dotnet ef dbcontext scaffold
    • bash
    1
    dotnet ef dbcontext scaffold "Server=10.0.75.1;Database=Sample;User ID=sa;Password=xxxxxx;Trusted_Connection=True;Integrated Security=False;" Microsoft.EntityFrameworkCore.SqlServer -o Models
  • 使用 Visual Studio - Package Manager Console

    Package Manager Console
    • bash
    1
    Scaffold-DbContext "Server=10.0.75.1;Database=Sample;User ID=sa;Password=xxxxxx;Trusted_Connection=True;Integrated Security=False;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

Scaffold 成功後,會看到 SampleDbContext.cs 被建立起來。 如下圖。

SampleDbContextSampleDbContext

調整連線字串的位置

你會看到 scaffold 後 SampleDbContext 裡面有連線字串 ,一般來說連線字串是跟 Source Code 分開的。 所以現在就是要將連線字串從 Source Code 拿掉,改由寫在 appsettings.json 裡面。

  1. 移除 SampleDbContext.cs 裡面的 optionsBuilder.UseSqlServer 程式碼,如下方範例,把連線字串那行拿掉,或是整個 OnConfiguring 方法移除也行

    移除程式碼
    • cs
    1
    2
    3
    4
    5
    6
    7
    8
    9
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
    if (!optionsBuilder.IsConfigured)
    {
    #warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
    // 移除
    // optionsBuilder.UseSqlServer("Server=10.0.75.1;Database=Sample;User ID=sa;Password=xxx;Trusted_Connection=True;Integrated Security=False;");
    }
    }
  2. 於 appsettings.json 加入連線字串,如下方範例。

    appsettings.json
    • json
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    {
    "Logging": {
    "LogLevel": {
    "Default": "Warning"
    }
    },
    "AllowedHosts": "*",
    "ConnectionStrings": {
    "Sample": "Server=10.0.75.1;Database=Sample;User ID=sa;Password=xxxx;Trusted_Connection=True;Integrated Security=False;"
    }
    }
  3. 於 Startup.cs 註冊 SampleDbContext 服務
    這個設定是要讓 SampleDbContext 可以被建構式注入。

    Startup.cs
    • cs
    1
    2
    3
    4
    5
    6
    public void ConfigureServices(IServiceCollection services)
    {
    ...
    services.AddDbContext<SampleContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("Sample")));
    }

接下來就可以正常使用 EF Core 開發了。

錯誤排除

其實今天寫這篇文章,是因為我在 Scaffold 資料庫的時候遇到下圖的錯誤 Trouble Connecting to sql server Login failed. The login is from an untrusted domain and cannot be used with Windows authentication。 這是因為當連線的 SQL Server 是不同 domain controller 的情況,且連線字串含有(預設) Integrated Security = True 時,SQL Server 會使用 windows credentials 來登入,這會讓你使用帳號密碼登入無效。

fail-scaffoldfail-scaffold

所以記得在連線字串加入 Integrated Security = false; 解決這個問題

延伸閱讀

[Getting Started with EF Core on ASP.NET Core with an Existing Database]
[Entity Framework Core tools reference - .NET CLI]
[EF Core - Connection Strings]