かずきのBlog@hatena

すきな言語は C# + XAML の組み合わせ。Azure Functions も好き。最近は Go 言語勉強中。日本マイクロソフトで働いていますが、ここに書いていることは個人的なメモなので会社の公式見解ではありません。

SQL Server CE 4.0 + Entity Framework 4.1 = お手軽お試し環境

SQL Server Compact Edition 4.0も出てきたし、Entity Framework 4.1のRCも出てきたし、お手軽サンプルプログラムを組むときのメンドクサイ障壁がどんどんなくなってきました!!ビバCodeFirst!!

ということで、CodeFirstさんはデフォだとSQL ServerさんにDB作ってくれるので、SQL Server CE 4.0にDB作ってくれるようにする方法をメモっておこうと思います。

Entity Frameworkをプロジェクトに追加

NuGetでサクッと出来ます。GUIから出来るといいのですが、どうもPackage Manager Consoleからやらないと怒られてしまいました。

PM> Install-Package -Project EFAndSQLCESample EntityFramework
You are downloading EntityFramework from Microsoft, the license agreement to which is available at http://go.microsoft.com/fwlink/?LinkID=211009. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.
'EntityFramework 4.1.10311.0' が正常にインストールされました
'EntityFramework 4.1.10311.0' が EFAndSQLCESample に正常に追加されました

CodeFirstでサクッとエンテティの定義

とりあえずサクッとエンテティとコンテキストを定義してしまいましょう。

namespace EFAndSQLCESample
{
    using System.ComponentModel.DataAnnotations;
    using System.Data.Entity;

    public class Person
    {
        public int PersonID { get; set; }

        [Required]
        public string Name { get; set; }
    }

    public class SampleContext : DbContext
    {
        public IDbSet<Person> People { get; set; }
    }
}

接続文字列を設定する

App.configを追加して、以下のように接続文字列を設定します。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
        <!-- コンテキストのクラス名と同じ名前で接続文字列を作成する -->
        <add name="SampleContext"
             connectionString="Data Source=|DataDirectory|SampleDatabase.sdf"
             providerName="System.Data.SqlServerCe.4.0"/>
    </connectionStrings>
</configuration>

適当にプログラムを作ってみる

CRUDしてるは表示してるだけの簡単なプログラムを作ってみました。

namespace EFAndSQLCESample
{
    using System;
    using System.Data.Entity;
    using System.Linq;

    class Program
    {
        static void Main(string[] args)
        {
            // 常にDBを削除して1から作る
            Database.SetInitializer(
                new DropCreateDatabaseAlways<SampleContext>());

            using (var ctx = new SampleContext())
            {
                // データの追加
                var p = new Person { Name = "田中 太郎" };
                ctx.People.Add(p);
                ctx.SaveChanges();
            }

            using (var ctx = new SampleContext())
            {
                // データの取得
                var p = ctx.People.First();
                Console.WriteLine("データ取得 : {0} {1}", p.PersonID, p.Name);

                // データの更新
                p.Name = "田中 改名太郎";
                ctx.SaveChanges();
            }

            using (var ctx = new SampleContext())
            {
                // データの取得(更新されてるか確認)
                var p = ctx.People.First();
                Console.WriteLine("データ取得 : {0} {1}", p.PersonID, p.Name);
                
                // データの削除
                ctx.People.Remove(p);
                ctx.SaveChanges();
            }

            using (var ctx = new SampleContext())
            {
                // 削除されているのを確認
                Console.WriteLine("Personテーブルの件数 : {0}", ctx.People.Count());
            }
        }
    }
}

実行すると、以下のような結果になります。

データ取得 : 1 田中 太郎
データ取得 : 1 田中 改名太郎
Personテーブルの件数 : 0

DBが作られてるのを確認する

プロジェクトフォルダの下の\bin\DebugにSampleDatabase.sdfが作成されているのが確認できます。

Webアプリで作るとApp_Dataの下にファイルが作られます。ちょっとしたアプリを作るときにはお手軽ですね。

サンプルのダウンロード

以下からダウンロードできます。