SQLite使用EF6的连接配置

本文介绍如何使用NuGet安装SQLite,并详细展示了配置文件中连接字符串的设置方法。此外,还提供了不通过配置文件直接在程序中建立连接的方式。

在配置文件中配置连接字符串

1. 使用nuget安装SQLite
Install-Package System.Data.SQLite

安装好后的依赖项有:

  • System.Data.SQLite.dll
  • System.Data.SQLite.EF6.dll
  • System.Data.SQLite.Linq.dll

    如果没有安装全,则需要手动安装需要的DLL

2. 安装时会自动配置配置文件。配置好的文件如下:
<?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>
  <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"/>
    </DbProviderFactories>
  </system.data>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v13.0"/>
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
      <provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6"/>
    </providers>
  </entityFramework>
  <connectionStrings>
    <add name="mydb" connectionString="data source=D:\my.db" providerName="System.Data.SQLite.EF6"/>
  </connectionStrings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>

==注意==

configSections配置节一定要在connectionStrings节之前,为了保险,我把它放在最后了。

其中,连接字符串是后来加上的。到这一步已经可以正常访问了。

3. 程序中使用
using (DbContext db = new DbContext("mydb"))
{
    //
}

不在配置连接字符串的配置

1.配置文件中不用配置connectionStrings节。
2.程序中使用
SQLiteConnection conn = new SQLiteConnection("Data Source=c:\my.db;");
using (DbContext db = new DbContext(conn,false))
{
    //
}

转载于:https://www.cnblogs.com/liuguangyin/p/6572734.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值