• SQLite for .NET (System.Data.SQLite)

    • introduction
    • how to use
      • Add references (Nuget to find “System.Data.SQLite”)

        • EntityFramework (can be upgraded to 6.2.0, already include EF and Linq)
        • System.Data.SQLite
        • System.Data.SQLite.Core
        • System.Data.SQLite.EF6 (can be removed)
        • System.Data.SQLite.Linq (can be removed)
      • Setup configuration file (in App.config)
        • connection string
        • db provider
      • Create custom context class

在App.Config或Web.config文件中配置数据库的连接字符串及使用到的Provider:

 <?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>
   <connectionStrings>
     <add name="PresetDataConnectionString" connectionString="data source=PresetData.db" providerName="System.Data.SQLite"/>
   </connectionStrings>
   <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"/>
     </providers>
   </entityFramework>
   <system.data>
     <DbProviderFactories>
       <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>
   <startup>
     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2"/>
   </startup>
 </configuration>

自定义Context类,用于操作数据库:

     /// <summary>
     /// Code First mode to use EF, on behalf of one DB
     /// </summary>
     public class UserDataContext : DbContext
     {
         public DbSet<FavoriteData> FavoriteDatas { get; set; }

         public UserDataContext(string connectionString)
             : base(new SQLiteConnection() { ConnectionString = connectionString }, true)
         {

         }

         /// <summary>
         /// avoid "no such table error" of __MigrationHistory and EdmMetadata in EF Code-First Mode
         /// </summary>
         static UserDataContext()
         {
             Database.SetInitializer<PresetDataContext>(null);
         }

         /// <summary>
         /// dummy code so that the compiler would detect that the reference is being used.
         /// make sure projects like VisualXml and VisualXml.Test have related dlls in output bin folder
         /// </summary>
         private static void FixProvidersNotAutoLoadProblem()
         {
             var _ = typeof(System.Data.SQLite.EF6.SQLiteProviderFactory);
             var __ = typeof(System.Data.SQLite.SQLiteFactory);
             //var ___ = typeof(System.Data.Entity.SqlServer.SqlProviderServices);
         }

         /// <summary>
         /// remove restriction of DbSet field names based on table names
         /// </summary>
         /// <param name="modelBuilder"></param>
         protected override void OnModelCreating(DbModelBuilder modelBuilder)
         {
             modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

             //modelBuilder.Configurations.AddFromAssembly(typeof(DefaultContext).Assembly);
             //modelBuilder.Configurations.AddFromAssembly(Assembly.GetExecutingAssembly());
         }
     }

也可以动态设置数据库连接字符串(动态往自定义的Context类的构造函数中传入拼接的连接字符串,userDataDBFilePath为db文件物理路径):

             SQLiteConnectionStringBuilder builder = SQLiteFactory.Instance.CreateConnectionStringBuilder() as SQLiteConnectionStringBuilder;

             // set up connection string for user data db in code
             builder.DataSource = userDataDBFilePath;
             builder.Password = GenerateEncryptedDBPwd();
             UserDataContext userDataDB = new UserDataContext(builder.ToString());

也可以直接使用ADO.NET操作数据库:

                SQLiteConnectionStringBuilder builder = SQLiteFactory.Instance.CreateConnectionStringBuilder() as SQLiteConnectionStringBuilder;
                builder.DataSource = "PresetData.db";
                using (SQLiteConnection conn = new SQLiteConnection(builder.ToString()))
                {
                    conn.Open();
                    string currentLanguageViewName = "vw_nc_variable_entire_info_" + Thread.CurrentThread.CurrentUICulture.Name.ToLowerInvariant().Replace('-', '_');
                    string sql = "select count(*) from sqlite_master where type = 'table' and name = '{" + currentLanguageViewName + "}'";
                    SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand();
                    cmd.CommandText = sql;
                    cmd.Connection = conn;
                    int tableInfoCount = Convert.ToInt32(cmd.ExecuteScalar());
                    )
                    {
                        modelBuilder.Entity<EntireInfo>().ToTable("vw_nc_variable_entire_info_" + Thread.CurrentThread.CurrentUICulture.Name.ToLowerInvariant().Replace('-', '_'));
                    }
                    else
                    {
                        modelBuilder.Entity<EntireInfo>().ToTable("vw_nc_variable_entire_info_en_us");
                    }
                    conn.Close();
                }

使用System.Data.SQLite及其EF模块操作SQLite数据库(文件)的更多相关文章

  1. Python使用cx_Oracle模块操作Oracle数据库--通过sql语句和存储操作

    https://www.jb51.net/article/125160.htm?utm_medium=referral  Python使用cx_Oracle调用Oracle存储过程的方法示例 http ...

  2. 【UWP】利用EF Core操作SQLite

    在以往开发中,一定要在vs中安装SQLite for Universal App Platform以及一款wrapper,如SQLitePCL.现在有了EntitfyFramewrok Core,我们 ...

  3. python用sqlite3模块操作sqlite数据库-乾颐堂

    SQLite是一个包含在C库中的轻量级数据库.它并不需要独立的维护进程,并且允许使用非标准变体(nonstandard variant)的SQL查询语句来访问数据库. 一些应用可是使用SQLite保存 ...

  4. ASP.NET Core使用EF Core操作MySql数据库

    ASP.NET Core操作MySql数据库, 这样整套环境都可以布署在Linux上 使用微软的 Microsoft.EntityFrameworkCore(2.1.4) 和MySql出的 MySql ...

  5. 【SQLite】 C#中操作SQlite

    简介 SQLite是轻量级数据库,具体的介绍请参考官网(SQLite官网).在WinForm的项目中需要采用独立的数据库访问,可在断网单机上使用,所以选择了SQLite! 使用 主要针对C#项目(Wi ...

  6. 以EF形式操作mysql数据库

    1.引入Nuget包: 2.书写EF操作上下文 public class MySqlContext:DbContext { protected override void OnConfiguring( ...

  7. nodeJS中使用mongoose模块操作mongodb数据库

    在实际运用中,对于数据库的操作我们不可能一直在cmd命令行中进行操作,一般情况下需要在node环境中来操作mongodb数据库,这时就需要引入mongoose模块来对数据库进行增删改查等操作. 首先, ...

  8. .Net版SQLite无法访问网络位置的数据库文件-winOpen,os_win.c 36702异常

    最近一个C#小程序,希望将SQLite数据库放在网络共享的位置,让多个客户端同时访问.却发现SQLite连接不上该网络位置的数据库,而如果数据库在本地则一切正常. 例如将SQLite数据库 test. ...

  9. .net core使用ef core操作mysql数据库

    新建.net core webapi项目 在NuGet包管理器中搜索 MySql.Data.EntityFrameworkCore并安装,安装的8.0.14版本,只安装这一个就够了 安装后创建Data ...

随机推荐

  1. vue -Missing space before value for key 'path'vue.js解决空格报错

    webpack.base.config.js文件注释掉下面的东西!! module: { rules: [      /*{        test: /\.(js|vue)$/,        lo ...

  2. ADDCOMPONENT之后立即(同步)调用AWAKE,但START却是所有AWAKE完成后才调用 的(异步)

    addcomponent 等价于 instance了一个组件,完成后立即从该点调用awake(). 等到游戏中所有组件都被awake()之后,start()才会被调用.示例如下: class MyTe ...

  3. 3.Hadoop集群搭建之Zookeeper安装

    前期准备 下载Zookeeper 3.4.5 若无特殊说明,则以下操作均在master节点上进行 1. 解压Zookeeper #直接解压Zookeeper压缩包 tar -zxvf zookeepe ...

  4. c# vs c++

    [c# vs c++] 1.在 C++ 中,类和结构实际上是相同的,而在 C# 中,它们很不一样.C# 类可以实现任意数量的接口,但只能从一个基类继承.而且,C# Struct不支持继承,也不支持显式 ...

  5. 超出div宽度范围的文字进行省略号省略,在鼠标移上去以后显示完整的内容

    一.前言 当我们在固定的范围内显示内容时,我们是希望能够完整显示的,然而往往事与愿违,文本会超出我们给定的范围,这时候怎么办呢? 二.超出范围,对文本进行省略号隐藏 先上图 代码很简单 div{ wi ...

  6. @property 修饰符

    原子性--- nonatomic 特质 在默认情况下,由编译器合成的方法会通过锁定机制确保其原子性(atomicity).如果属性具备 nonatomic 特质,则不使用同步锁.请注意,尽管没有名为“ ...

  7. 669. Trim a Binary Search Tree修剪二叉搜索树

    [抄题]: Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so ...

  8. vagrant 安装与配置

    1.下载vagrant的安装包 http://downloads.vagrantup.com/ 2.解压安装 3.安装box环境   4.安装成功显示 5.提示要安装virbox

  9. spring4-2-bean配置-6-使用外部属性文件

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAk0AAAFGCAIAAAD4tzxRAAAgAElEQVR4nO2d27HsOm+tOxWn4CeXAm ...

  10. 53-C++ CH08 01

     http://lx.lanqiao.cn/problem.page?gpid=T407 算法训练 C++ CH08 01   时间限制:1.0s   内存限制:256.0MB      问题描述 已 ...