1
0

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 1 year has passed since last update.

.Net6 EFCore6 seedデータ

Posted at

はじめに

環境

C#
.Net6
EFCore6
Blazor

Seed は公式があるのですが
どのファイルに追加するかがわかりずらいです。
https://docs.microsoft.com/ja-jp/ef/core/modeling/data-seeding

実装

/Server/Data/AppDbContext.cs

namespace BlazorApp.Server.Data
{
    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions options) : base(options)
        {}

        public DbSet<Building> Buildings => Set<Building>();


        // エラーを表示するのに必要だとか
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.EnableSensitiveDataLogging();
        }

       // 
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Building>().HasData(
                new { BuildingId = 1, OwnerId = 2, BuildingName = "集合住宅A", BuildingType = BuildingTypeEnum.HousingComplex, BuildingDetail = "駅近です" }
            );
        }
   }
}

Enumをつかっているケース

BuildingType = BuildingTypeEnum.HousingComplex  のように代入するのですが


他のEnumでは
 RoomStaus = 0  こんな感じでも代入できます

命名規則の関係かもしれませんが、よくわかってないです。

Dataの反映

dotbet ef migration add SeedData
database ef database update

これでOK
.NetではSeedはMigrationの一部なんですね
またローカルと本番でSeed有無を分けたりしないのが基本のようです。

他のフレームワークとの違いですね

次はAPI作成ですが、こちらは簡単そうなので
ようやくBlazorに取り掛かれそう。

1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?