• Nuget:Install-Package System.Data.SQLite.EF6
  • 配置文件(注意有坑,自动生成的配置文件是没法用的):
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?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>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <entityFramework>
    <providers>
      <provider invariantName="System.Data.SQLite" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
      <provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
    </providers>
  </entityFramework>
  <connectionStrings>
    <add name="dataContext" connectionString="Data Source=data.s3db" providerName="System.Data.SQLite"/>
  </connectionStrings>
  <system.data>
    <DbProviderFactories>
      <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" />
      <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>
</configuration>
  • 注意有第二坑: sqlite的这个EF库并不支持CodeFirst的表自动创建,所以,请使用命令行或者是sqlite的其他管理工具创建数据库并进行表结构设计。(管理工具尝试了几个,还是用SQLiteStudio顺手: http://sqlitestudio.pl )
  • 注意还有坑: sqlite3不允许用除integer以外的类型作为自增主键,对应的C#类型是long。
  • 代码,终于可以愉快的用起来了
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
    public class DataContext:DbContext
    {
        public DbSet<Article> Article { get; set; }
    }

    public class Article
    {
        public long ID { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
    }

    public static void Add(Article article)
    {
        using (var context = new DataContext())
        {
            context.Article.Add(tm);
            context.SaveChanges();
        }
    }