ハロの外部記憶インターフェイス

そろそろ覚える努力が必要かも…

.NetのEntityFrameworkCoreでSQL Server接続を設定してみた

EntityFrameworkCore設定

.NetプロジェクトにEntityFrameworkCoreを設定する歩法についてメモする。
今回の対象はSql Serverにするが、対象はNugetパッケージでインストールする物によって変わる。

ProjectにNugetパッケージを追加する。

バージョンはテスト時点のバージョン

 - Microsoft.EntityFrameworkCore.Design v5.0.11
 - Microsoft.EnrityFrameworkCore.SqlServer v5.0.11
 - Microsoft.EnrityFrameworkCore.Tools v5.0.11

※基本は「 Sqlserver」だけあれば接続可能

EntityFrameworkCore CLI Toolsのインストール

dotnet tool install --global dotnet-ef

EF Core ツールリファレンス (.NET CLI)-EF Core | Microsoft Docs

DbContextとModels作成

対象のプロジェクトファイルがあるフォルダーまで移動後、実行

dotnet ef dbcontext scaffold
 "Server=127.0.0.1;Database=testdb;User Id=sa;Password=password"
 Microsoft.EntityFrameworkCore.SqlServer
 -o Models

※生成ファイルはプロジェクトのModelsフォルダーに生成される。

接続情報の環境設定化

appsetting.json

{
  "ConnectionStrings": {
    "DBConnection": "Server=127.0.0.1;Database=testdb;User Id=sa;Password=password"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information",
      "Microsoft.EntityFrameworkCore.Database.Command": "Information"
    }
  },
  "AllowedHosts": "*"
}
  • ConnectionStrings : 接続文字列情報
  • Microsoft.EntityFrameworkCore.Database.Command : SQLログ出力のため追加

Startup.cs修正

using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
public void ConfigureServices(IServiceCollection services)
{
#if DEBUG
    services.AddDbContextFactory<testdbContext>(opt => 
        opt.UseSqlServer(Configuration.GetConnectionString("DBConnection"))
        .EnableSensitiveDataLogging());
#else
    services.AddDbContextFactory<testdbContext>(
        options => options.UseSqlServer(
            Configuration.GetConnectionString("DBConnection")));
#endif
    services.AddRazorPages();
    services.AddServerSideBlazor();
    .....
}
  • DEBUG時にはEnableSensitiveDataLoggingにより、SQLログを出力する。

使用例

razor

@using Microsoft.EntityFrameworkCore
@implements IDisposable
@inject IDbContextFactory<testdbContext> DbFactory

@code {
private MyProject.Models.testdb context;
protected override async Task OnInitializedAsync()
{
    Busy = true;
    try
    {
        context = DbFactory.CreateDbContext();
        List = await context.Contacts
            .SingleOrDefaultAsync(c => c.Id == ContactId);
    }
    finally
    {
        Busy = false;
    }
    await base.OnInitializedAsync();
}
}

ASP.NET Core Blazor Server と Entity Framework Core (EFCore) | Microsoft Docs ASP.NET Core での依存関係の挿入 | Microsoft Docs