准备
EntityFramework 6
System.Data.sqlite.EF6
sqlite.CodeFirst
设置
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> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" /> </startup> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory,EntityFramework"> <parameters> <parameter value="v13.0" /> </parameters> </defaultConnectionFactory> <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> <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> </configuration>
读取DB
public class MyContext : DbContext { public MyContext(DbConnection conn) : base(conn,true) { }
使用CodeFirst写入DB
class MyContext : DbContext { public MyMdContext(DbConnection conn) :base(conn,true) { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { var sqliteConnectionInitializer = new sqliteCreateDatabaseIfNotExists<MyContext>(modelBuilder); Database.SetInitializer(sqliteConnectionInitializer); base.OnModelCreating(modelBuilder); } }
数据映射
如果key类型为整形,必须使用Int64。sql数据库中,INT为32位,INTEGER为64位
(1) EF创建表的时候,整形的key为Int64,即使定义的为int
(2) EF读取表的时候,若定义的key为INT,则用int,若INTEGER,则为Int64
故定义KEY,必须使用INTEGER。EF不会把数据库中int类型映射为Int64
输入插入
默认情况下,每次插入数据都会建立索引,故随着插入数据增多,会越来越慢。所以需要关闭此功能:
context.Configuration.AutoDetectChangesEnabled = false;在context.SaveChanges的时候建立一次索引即可。