主にプログラミング関連のメモ帳 ♪(✿╹ヮ╹)ノ
書いてあるコードは自己責任でご自由にどうぞ。記事本文の無断転載は禁止です。
2016/10/13
Entity Framework Core を使ったアプリを UWP で作ったので、
ライブラリとツールの使い方をメモしておきます。
基本、ドキュメントの Getting Started 通りにすればいけます。
はじめに、 NuGet から以下のパッケージをインストールします。
Microsoft.EntityFrameworkCore.Sqlite
Microsoft.EntityFrameworkCore.Tools
インストールが終わったら、適当にモデルクラスを作成します。
public class ShoppingContext : DbContext
{
public DbSet<Item> Items { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite($"Filename=Shopping.db");
}
}
public class Item
{
public int ItemId { get; set; }
public string Name { get; set; }
public int Price { get; set; }
}
次に、データベースを作成します。
この時、 EntityFrameworkCore.Tools のコマンドを叩くと例外が発生するので、
以下の内容を App.config
に記述しておきます。
なお、 1.0.1 ではドキュメントにあるものそのままでは例外が発生します。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.IO.FileSystem.Primitives" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="4.0.0.0" newVersion="4.0.1.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Threading.Overlapped" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="4.0.0.0" newVersion="4.0.1.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.ComponentModel.Annotations" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="4.1.0.0" newVersion="4.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.EntityFrameworkCore" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="1.0.0.0" newVersion="1.0.1.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.EntityFrameworkCore.Relational" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="1.0.0.0" newVersion="1.0.1.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
解決方法のコメントはこちら
Add-Migration doesn't work in a UWP project with EF Core 1.0.1
保存したら、パッケージマネージャーコンソールから、 Add-Migration
コマンドを実行します。
こんな感じ。
PM> Add-Migration MyFirstMigration
実行すると、 Migrations
以下にマイグレーション用のソースが生成されます。
次に、 App.xaml.cs
にマイグレーション用のコードを記述します。
public App()
{
using (var dbContext = new ShoppingContext())
dbContext.Migrate();
}
あとは、好きなところから使うだけです。