ASP.NET CoreのMVCアプリを作るときのデータベース接続設定です。namespace
は各自で書き換えてください。設定は、SQLserverを使用する前提で記述しています。
DBコンテキストクラスの作成
DBコンテキストクラスを継承したDB接続用のコンテキストクラスを作成します。
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_Connection
をtrue
にします。反対に、SQLSever認証などを使用する場合は、false
にしてユーザー名とパスワードを下記のように記述します。
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=asp_blog;user=sa;password=P@sswOrd123;Trusted_Connection=false;"
},
準備ができたらマイグレーション開始
上記の設定が済んだら、マイグレーションコマンドを実行します。Windowsの場合は、パッケージマネージャーコンソールから以下のコマンドを打ちます。
add-migration [マイグレーション名]
update-database
add-migration
で作成されたマイグレーションファイルを元にupdate-database
コマンドによってデータベースにテーブルが作成されます。
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)
バージョンについてもエラーが出ました。
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.
こんなときは、バージョンの設定を個別のアプリではなく、グローバルに更新する必要があります。
dotnet tool update --global dotnet-ef
visual studio for mac ですが、これでマイグレーションができるようになりました。