1
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ASP.NET Core MVC の DB接続の設定

Last updated at Posted at 2020-10-24

ASP.NET CoreのMVCアプリを作るときのデータベース接続設定です。namespaceは各自で書き換えてください。設定は、SQLserverを使用する前提で記述しています。

DBコンテキストクラスの作成

DBコンテキストクラスを継承したDB接続用のコンテキストクラスを作成します。

ApplicationDbContext.cs
using Microsoft.EntityFrameworkCore;
using ASP.NET_Blog.Models;

namespace ASP.NET_Blog.Data
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {
        }
        
        // あらかじめ作成したモデルの中でマイグレーションで生成したい物を記述
        public DbSet<User> User { get; set; }
    }
}

DB接続文字列の設定

appsettings.jsonで接続文字列の設定を自身のデータベース情報に変更します。OS認証(例:Windows認証など)を使う場合、Trusted_Connectiontrueにします。反対に、SQLSever認証などを使用する場合は、falseにしてユーザー名とパスワードを下記のように記述します。

appsettings.json
"ConnectionStrings": {
        "DefaultConnection": "Server=localhost;Database=asp_blog;user=sa;password=P@sswOrd123;Trusted_Connection=false;"
    },

準備ができたらマイグレーション開始

上記の設定が済んだら、マイグレーションコマンドを実行します。Windowsの場合は、パッケージマネージャーコンソールから以下のコマンドを打ちます。

windows
add-migration [マイグレーション名]
update-database

add-migrationで作成されたマイグレーションファイルを元にupdate-databaseコマンドによってデータベースにテーブルが作成されます。

macの場合は、ツールバーの表示→パッド→ターミナルか、プロジェクトファイルを右クリック→ツール→ターミナルパッドで開く、でターミナルを開いてコマンドを打ちます。

Mac
dotnet ef migrations add [マイグレーション名]
dotnet ef database update

エラーが出た場合

設定中にこんなエラーが出ました。

SQLServer認証の設定で、ユーザー名やパスワードを入れ忘れたり、間違っている場合は認証エラーのメッセージが出ます。

Cannot authenticate using Kerberos. Ensure Kerberos has been initialized on the client with 'kinit' and a Service Principal Name has been registered for the SQL Server to allow Kerberos authentication.
ErrorCode=InternalError, Exception=Interop+NetSecurityNative+GssApiException: GSSAPI operation failed with error -  An unsupported mechanism was requested (unknown mech-code 0 for mech unknown).
   at System.Net.Security.NegotiateStreamPal.GssInitSecurityContext(SafeGssContextHandle& context, SafeGssCredHandle credential, Boolean isNtlm, SafeGssNameHandle targetName, GssFlags inFlags, Byte[] buffer, Byte[]& outputBuffer, UInt32& outFlags, Int32& isNtlmUsed)
   at System.Net.Security.NegotiateStreamPal.EstablishSecurityContext(SafeFreeNegoCredentials credential, SafeDeleteContext& context, String targetName, ContextFlagsPal inFlags, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, ContextFlagsPal& outFlags)
   at Microsoft.Data.SqlClient.SNI.SNIProxy.GenSspiClientContext(SspiClientContextStatus sspiClientContextStatus, Byte[] receivedBuff, Byte[]& sendBuff, Byte[] serverName)
   at Microsoft.Data.SqlClient.SNI.TdsParserStateObjectManaged.GenerateSspiClientContext(Byte[] receivedBuff, UInt32 receivedLength, Byte[]& sendBuff, UInt32& sendLength, Byte[] _sniSpnBuffer)
   at Microsoft.Data.SqlClient.TdsParser.SNISSPIData(Byte[] receivedBuff, UInt32 receivedLength, Byte[]& sendBuff, UInt32& sendLength)

バージョンについてもエラーが出ました。

error
The EF Core tools version '3.1.6' is older than that of the runtime '3.1.9'. Update the tools for the latest features and bug fixes.

こんなときは、バージョンの設定を個別のアプリではなく、グローバルに更新する必要があります。

Mac
dotnet tool update --global dotnet-ef

visual studio for mac ですが、これでマイグレーションができるようになりました。

1
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?