Entity Framework 和 Sqlite


準備

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




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章