Entity Framework 和 Sqlite

来源:互联网 发布:mac百度云下载速度慢 编辑:程序博客网 时间:2024/05/22 14:38


准备

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的时候建立一次索引即可。




原创粉丝点击