第一步:在NuGet安裝System.Data.Sqlite程式包
第二步:產生實體類
我試了很多次,嘗試用Entity Framework Power Tools Beta 4串連Sqlite產生實體類,但都失敗了,最後的解決辦法是在SQL Server建立一個相同結構的庫,EF Power Tools串連SQL Server產生實體類,產生完後記得修改設定檔中資料庫連接字串:
<add name="testContext" connectionString="Data Source=F:\test.db;failifmissing=false" providerName="System.Data.SQLite.EF6" />
注意:EntityFramework 6串連Sqlite資料庫提供者不是System.Data.SQLite,得用System.Data.SQLite.EF6,這在設定檔(App.config)中有解釋說明。
第三步:最終App.config內容如下
引用內容
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="testContext" connectionString="Data Source=F:\test.db;failifmissing=false"
providerName="System.Data.SQLite.EF6" />
</connectionStrings>
<system.data>
<!--
NOTE: The extra "remove" element below is to prevent the design-time
support components within EF6 from selecting the legacy ADO.NET
provider for SQLite (i.e. the one without any EF6 support). It
appears to only consider the first ADO.NET provider in the list
within the resulting "app.config" or "web.config" file.
-->
<DbProviderFactories>
<add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".NET Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
<remove invariant="System.Data.SQLite" />
<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" />
</DbProviderFactories>
</system.data>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.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>
</configuration>
第四步:測試程式
using(testContext context = new testContext())
{
List<Person> people = context.People.ToList();
foreach(Person item in people)
{
Console.WriteLine("{0},{1}", item.Name, item.Age);
}
}