Entity Framework 6连接Sqlite数据库示例

第一步:在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);
    }
}



评论: 0 | 引用: 0 | 查看次数: 5834
发表评论
登录后再发表评论!