ASP.NET core MVC DBからスキャフォールドを使用してCRUDを作成する
- 作成日 2022.04.09
- ASP.NET Core
- ASP.NET Core
ASP.NET core MVCで、DBからスキャフォールドを使用してCRUDを作成する手順を記述してます。.NETのバージョンは6を使用してます。
環境
- OS windows10 pro
- IDE Visual Studio 2022
- .NET 6
プロジェクト作成
ここでは、「ASP.NET Core Web アプリ(Model-View-Controller)」を選択してプロジェクトを作成してます。
SQLServer
DB「hoge」にある「member」テーブルを使用します。
「member」テーブルには、以下のデータが存在します。
パッケージ追加
使用するパッケージを追加しておきます。
「ツール」 > 「NuGet パッケージ マネージャー」 > 「パッケージ マネージャー コンソール」を選択します。
以下の2つを作成したプロジェクトに追加します。
PM> Install-Package -ProjectName プロジェクト名 -Id Microsoft.EntityFrameworkCore.SqlServer
PM> Install-Package -ProjectName プロジェクト名 -Id Microsoft.EntityFrameworkCore.Tools
Model作成
ここではDBに接続して作成します。Scaffold-DbContextを使用して、以下のコマンドを実行します。
DB名 : hoge
ホスト : 192.168.xxx.xxx
ユーザー : sa
パスワード : password
modelを作成するフォルダ : Models
コンテキスト名 : MemberDbContext
PM> Scaffold-DbContext -Provider Microsoft.EntityFrameworkCore.SqlServer -Connection "Data Source=192.168.xxx.xxx;Database=hoge;user id=sa;password=password" -f -OutputDir "Models" -Context "MemberDbContext" -UseDatabaseNames -DataAnnotations
Modelが作成されていることが確認できます。
「MemberDbContext.cs」に記述されているDB接続情報はコメントアウトしておきます。
// 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. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
// optionsBuilder.UseSqlServer("Data Source=192.168.xxx.xxx;Database=hoge;user id=sa;password=password");
// }
// }
DB接続情報
sqlserverと接続できるように接続情報を追加します。
「appsettings.json」に、以下のコードを追加します。
「ConnectionStrings」を追加します。
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Server=192.168.xxx.xxx;Database=hoge;User ID=sa;Password=password;"
}
}
サービス登録
サービスに、コンテキストを登録します。「Program.cs」を編集します。
さきほど作成した接続情報「DefaultConnection」を使用して「MemberDbContext」を登録します。
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
// 追加
builder.Services.AddDbContext<MemberDbContext>(
options => options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")
)
);
スキャフォールド
スキャフォールドを使用して、ViewとControllersを作成します。
「Controllers」フォルダを右クリックして「新規スキャフォールディングアイテム」をクリックします。
「Entity Frameworkを使用したビューがあるMVCコントローラー」を選択して、「追加」をクリックします。
さきほど、作成したモデルとデータコンテキストを選択して、「追加」をクリックします。
実行
「F5」キーでデバックを実行して、起動します。
http://localhost:ポート番号/members/ にアクセスするとCRUDが作成されていることが確認できます。
-
前の記事
MySQL jsonデータからkeyのみを取得する 2022.04.09
-
次の記事
pgadmin コメントアウトを一括で実行する 2022.04.09
コメントを書く