C# EF SQLite 配置

依赖

EntityFramework
Stub.System.Data.SQLite.Core.NetFramework
System.Data.SQLite
System.Data.SQLite.Core
System.Data.SQLite.EF6
System.Data.SQLite.Linq

配置文件

<?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" />
  </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>
  <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>
  <connectionStrings>
    <!-- SQLite数据库连接 -->
    <add name="SQLiteContext" connectionString="Data Source=|DataDirectory|\Database\xxxxxxxx.sqlite;" providerName="System.Data.SQLite.EF6" />
  </connectionStrings>
  ......
</configuration>

 数据库上下文

public class SQLiteContext : DbContext
{
    public DbSet<Mod1> Mod1s { set; get; }
    public DbSet<Mod2> Mod2s { set; get; }
    ......
}

EF暖机(可以写在初始化的函数中,用于解决首次查询慢的问题)

// EF暖机(SQLite)
using (SQLiteContext dbContext = new SQLiteContext())
{
    var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
    var mappingCollection = (StorageMappingItemCollection)objectContext.MetadataWorkspace.GetItemCollection(DataSpace.CSSpace);
    mappingCollection.GenerateViews(new List<EdmSchemaError>());
}

 

posted @ 2022-10-10 12:18  Mr_Xul  阅读(375)  评论(0编辑  收藏  举报