DB Firstとは DB Firstは、既存のデータベースからEntity Frameworkのモデルを生成するアプローチです。以下の手順に従って、Visual Studio 2015でEF6とSQLiteデータベースを使用してDB Firstモードを設定します。
- 公式サイトから32ビットのSQLiteドライバーをダウンロードし、インストールします。古いバージョンのドライバーがインストールされている場合は、アンインストールして最新版をインストールします。
- NuGetパッケージマネージャーを使用して、System.Data.SQLiteおよびその依存関係を取得します。
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework" version="6.0.0" targetFramework="net40" />
<package id="EntityFramework.zh-Hans" version="6.1.3" targetFramework="net40" />
<package id="System.Data.SQLite" version="1.0.101.0" targetFramework="net40" />
<package id="System.Data.SQLite.Core" version="1.0.101.0" targetFramework="net40" />
<package id="System.Data.SQLite.EF6" version="1.0.101.0" targetFramework="net40" />
<package id="System.Data.SQLite.Linq" version="1.0.101.0" targetFramework="net40" />
</packages>
- データベースファイルはApp_Dataディレクトリに配置します。
- エンティティモデルを追加します。
- 構成ファイルの接続文字列を修正します(デフォルトでは絶対パスが使用されるため、App_Dataディレクトリへの相対パスに変更します)。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v13.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
</providers>
</entityFramework>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SQLite.EF6" />
<add name="SQLite Data Provider (Entity Framework 6)" invariant="System.Data.SQLite.EF6" description=".NET Framework Data Provider for SQLite (Entity Framework 6)" type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6" />
<remove invariant="System.Data.SQLite" />
<add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".NET Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
</DbProviderFactories>
</system.data>
<connectionStrings>
<add name="JianBoShiEntities" connectionString="metadata=res://*/JianBoShiContent.csdl|res://*/JianBoShiContent.ssdl|res://*/JianBoShiContent.msl;provider=System.Data.SQLite.EF6;provider connection string="data source=|DataDirectory|\JianBoShi.db"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
- コードでの使用方法
using (var context = new JianBoShiEntities())
{
Repeater1.DataSource = context.ProductCategories.ToList();
Repeater1.DataBind();
}