[EF Core 3] 安裝 EF Core 3

EF Core 跟 EF 6 的安裝方式有很大的不同,記錄一下安裝步驟

開發工具

  • VS 2019 Enterprise

安裝步驟

開一個測試專案

 

1.Install EF Core DB Provider

選擇你的 DB Provider,我要使用 SQL Server 演練,所以安裝以下,擇一執行

.NET Core CLI:

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

Visual Studio PowerShell:

Install-Package Microsoft.EntityFrameworkCore.SqlServer

\更多的 Provider 請參考以下

https://www.entityframeworktutorial.net/efcore/entity-framework-core.aspx#efcore-db-providers

2.Install EF Core Tools for PMC

這個可以在 VS IDE 執行 scaffolding、migration 命令,擇一執行

.NET Core CLI:

dotnet add package Microsoft.EntityFrameworkCore.Tools

Visual Studio PowerShell:

Install-Package Microsoft.EntityFrameworkCore.Tools

 

或者是安裝本機全域通用工具

.NET Core CLI:

安裝

dotnet tool install --global dotnet-ef

更新

dotnet tool update --global dotnet-ef

更多的命令請參考以下

EF Core tools reference (.NET CLI) - EF Core | Microsoft Docs

EF Core tools reference (Package Manager Console) - EF Core | Microsoft Docs

在 Package Manager Console 輸入 get-help entityframework

 

3.Install EF Core Tools for dotnet CLI

當沒有了 VS IDE,仍然可以透過 CLI 執行 EF Core 的命令,擇一執行

.NET Core CLI:

dotnet add package Microsoft.EntityFrameworkCore.Tools.DotNet

Visual Studio PowerShell:

Install-Package Microsoft.EntityFrameworkCore.Tools.DotNet

更多的 cli 命令請參考以下
https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dotnet

 

還需要在專案組態設定加入 <DotNetCliToolReference>

Add <DotNetCliToolReference> tag at *.csproj

<Project Sdk="Microsoft.NET.Sdk">
 
  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
 
    <IsPackable>false</IsPackable>
  </PropertyGroup>
 
  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.3" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.0.1" />
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.2.0" />
    <PackageReference Include="MSTest.TestAdapter" Version="1.4.0" />
    <PackageReference Include="MSTest.TestFramework" Version="1.4.0" />
    <PackageReference Include="coverlet.collector" Version="1.0.1" />
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.3" />
  </ItemGroup>
 
  <ItemGroup>
    <None Update="appsettings.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
  </ItemGroup>
 
</Project>

 

確定是否安裝完成?設定完成後Build,用命令提示字元 ,在專案的根目錄輸入 dotnet ef

 

4.Generate POCO

當資料庫已經存在的時候,可以利用 Scaffold-DbContext 來產生 POCO

Scaffold-DbContext (PMC = Package Manager Console)

Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=LabEmployee;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

dotnet ef dbcontext scaffold

dotnet ef dbcontext scaffold "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models

 

結果如下圖


 

 

5.Read Config Json File

讀取 Json 設定檔需要以下套件,擇一執行

.NET Core CLI:

dotnet add package Microsoft.Extensions.Configuration.Json

Visual Studio PowerShell:

Install-Package Microsoft.Extensions.Configuration.Json

@ appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=LabEmployee;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

 

@ UnitTest1.cs

由 Scaffold 產生出來的 DbContext 有一個建構函數是 DbContextOptions,我們需要從這裡拿到組態設定的資料,程式碼如下

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        var configuration = new ConfigurationBuilder()
                            .AddJsonFile("appsettings.json")
                            .Build();
 
        var connectionString = configuration.GetConnectionString("DefaultConnection");
        var dbContextOptions = new DbContextOptionsBuilder<LabEmployeeContext>()
                               .UseSqlServer(connectionString)
                               .Options;
        var dbContext = new LabEmployeeContext(dbContextOptions);
 
        var employees = dbContext.Employee.ToList();
        Assert.AreEqual(true, employees.Count > 0);
    }
}

 

把讀取組態的功能抽出來

public static class DbOptionsFactory
{
    public static DbContextOptions<LabEmployeeContext> DbContextOptions { get; }
 
    static DbOptionsFactory()
    {
        var configuration = new ConfigurationBuilder()
                     .AddJsonFile("appsettings.json")
                     .Build();
        var connectionString = configuration.GetConnectionString("DefaultConnection");
 
        DbContextOptions = new DbContextOptionsBuilder<LabEmployeeContext>()
                           .UseSqlServer(connectionString)
                           .Options;
    }
}

 

使用起來就方便些了

[TestMethod]
public void TestMethod1()
{
    var dbContext = new LabEmployeeContext(DbOptionsFactory.DbContextOptions);
 
    var employees = dbContext.Employee.ToList();
    Assert.AreEqual(true, employees.Count > 0);
}

 

若要使用 CLI ,dotnet 開頭的命令有以下必要條件

下圖出自:https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/

 

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo