読者です 読者をやめる 読者になる 読者になる

1.21 jigowatts

Great Scott!

Entity Framework~Code-Based Migration - 初期データを登録する

Visual Studio C# SQLServer

概要

前回の続きで、パッケージマネージャーコンソールからEntity Frameworkを操作して、データベースに初期データを登録します。

環境

Microsoft Visual Studio Community 2013
Entity Framework 6.1.3

実践

1.Seedメソッド

Migrations/Configuration.cs

namespace ConsoleApplication1.Migrations
{
    using ConsoleApplication1.DAL;
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<ConsoleApplication1.DAL.EFContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(ConsoleApplication1.DAL.EFContext context)
        {
            context.People.AddOrUpdate(p => p.Name,
                new Person { Name = "Bob", PhoneNumber = "123", Address = "N01", Job = "A01", UpdatedBy = "SYSTEM", UpdateDate = DateTime.Now },
                new Person { Name = "Alice", PhoneNumber = "456", Address = "E01", Job = "B01", UpdatedBy = "SYSTEM", UpdateDate = DateTime.Now },
                new Person { Name = "Tracy", PhoneNumber = "789", Address = "S01", Job = "C01", UpdatedBy = "SYSTEM", UpdateDate = DateTime.Now },
                new Person { Name = "Ken", PhoneNumber = "147", Address = "W01", Job = "D01", UpdatedBy = "SYSTEM", UpdateDate = DateTime.Now }
                );
        }
    }
}

2.データベースへ反映

PM> Update-Database

f:id:sh_yoshida:20150611184559p:plain

結果

Seeedメソッドが実行されてデータベースへ初期データが登録されました。
f:id:sh_yoshida:20150611184922p:plain

sh-yoshida.hatenablog.com