• 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:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <configuration>
  3. <configSections>
  4. <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
  5. <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
  6. </configSections>
  7. <connectionStrings>
  8. <add name="PresetDataConnectionString" connectionString="data source=PresetData.db" providerName="System.Data.SQLite"/>
  9. </connectionStrings>
  10. <entityFramework>
  11. <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
  12. <parameters>
  13. <parameter value="v13.0"/>
  14. </parameters>
  15. </defaultConnectionFactory>
  16. <providers>
  17. <provider invariantName="System.Data.SQLite" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6"/>
  18. </providers>
  19. </entityFramework>
  20. <system.data>
  21. <DbProviderFactories>
  22. <remove invariant="System.Data.SQLite"/>
  23. <add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".NET Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite"/>
  24. </DbProviderFactories>
  25. </system.data>
  26. <startup>
  27. <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2"/>
  28. </startup>
  29. </configuration>

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

  1. /// <summary>
  2. /// Code First mode to use EF, on behalf of one DB
  3. /// </summary>
  4. public class UserDataContext : DbContext
  5. {
  6. public DbSet<FavoriteData> FavoriteDatas { get; set; }
  7.  
  8. public UserDataContext(string connectionString)
  9. : base(new SQLiteConnection() { ConnectionString = connectionString }, true)
  10. {
  11.  
  12. }
  13.  
  14. /// <summary>
  15. /// avoid "no such table error" of __MigrationHistory and EdmMetadata in EF Code-First Mode
  16. /// </summary>
  17. static UserDataContext()
  18. {
  19. Database.SetInitializer<PresetDataContext>(null);
  20. }
  21.  
  22. /// <summary>
  23. /// dummy code so that the compiler would detect that the reference is being used.
  24. /// make sure projects like VisualXml and VisualXml.Test have related dlls in output bin folder
  25. /// </summary>
  26. private static void FixProvidersNotAutoLoadProblem()
  27. {
  28. var _ = typeof(System.Data.SQLite.EF6.SQLiteProviderFactory);
  29. var __ = typeof(System.Data.SQLite.SQLiteFactory);
  30. //var ___ = typeof(System.Data.Entity.SqlServer.SqlProviderServices);
  31. }
  32.  
  33. /// <summary>
  34. /// remove restriction of DbSet field names based on table names
  35. /// </summary>
  36. /// <param name="modelBuilder"></param>
  37. protected override void OnModelCreating(DbModelBuilder modelBuilder)
  38. {
  39. modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
  40.  
  41. //modelBuilder.Configurations.AddFromAssembly(typeof(DefaultContext).Assembly);
  42. //modelBuilder.Configurations.AddFromAssembly(Assembly.GetExecutingAssembly());
  43. }
  44. }

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

  1. SQLiteConnectionStringBuilder builder = SQLiteFactory.Instance.CreateConnectionStringBuilder() as SQLiteConnectionStringBuilder;
  2.  
  3. // set up connection string for user data db in code
  4. builder.DataSource = userDataDBFilePath;
  5. builder.Password = GenerateEncryptedDBPwd();
  6. UserDataContext userDataDB = new UserDataContext(builder.ToString());

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

  1. SQLiteConnectionStringBuilder builder = SQLiteFactory.Instance.CreateConnectionStringBuilder() as SQLiteConnectionStringBuilder;
  2. builder.DataSource = "PresetData.db";
  3. using (SQLiteConnection conn = new SQLiteConnection(builder.ToString()))
  4. {
  5. conn.Open();
  6. string currentLanguageViewName = "vw_nc_variable_entire_info_" + Thread.CurrentThread.CurrentUICulture.Name.ToLowerInvariant().Replace('-', '_');
  7. string sql = "select count(*) from sqlite_master where type = 'table' and name = '{" + currentLanguageViewName + "}'";
  8. SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand();
  9. cmd.CommandText = sql;
  10. cmd.Connection = conn;
  11. int tableInfoCount = Convert.ToInt32(cmd.ExecuteScalar());
  12. )
  13. {
  14. modelBuilder.Entity<EntireInfo>().ToTable("vw_nc_variable_entire_info_" + Thread.CurrentThread.CurrentUICulture.Name.ToLowerInvariant().Replace('-', '_'));
  15. }
  16. else
  17. {
  18. modelBuilder.Entity<EntireInfo>().ToTable("vw_nc_variable_entire_info_en_us");
  19. }
  20. conn.Close();
  21. }

使用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. MySQL修改redo_log_size

    MySQL5.5 步骤如下: 1. set global innodb_fast_shutdown = 0; 2. mysqladmin shutdown 3. 修改my.cnf innodb_log ...

  2. Elasticsearch-2.4.3的下载(图文详解)

    第一步:进入Elasticsearch的官网 https://www.elastic.co/ 第二步:点击downloads https://www.elastic.co/downloads 第三步: ...

  3. 增强MyEclipse提示功能

    当我们使用MyEclipse编辑代码的时候按住“Ctrl+/”,就能获得代码提示,或者使用“.”的时候就会“点”出属性或方法等,而且提示还会有延迟. 如果我们想无论是按下“.”.“Ctrl+/”甚至是 ...

  4. windows版mongodb不知道安装在哪儿

    情景还原: 从官网:点击打开链接 下载了 MongoDB-win32-x86_64-2.6.12-signed.msi文件后, 右键安装,各种Next后,没有选择路径,就安装结束了!! 任务管理器里面 ...

  5. apktool.bat

    @echo off if "%PATH_BASE%" == "" set PATH_BASE=%PATH% set PATH=%CD%;%PATH_BASE%; ...

  6. Linux实战教学笔记43:squid代理与缓存实践(二)

    第6章 squid代理模式案例 6.1 squid传统正向代理生产使用案例 6.1.1 squid传统正向代理两种方案 (1)普通代理服务器 作为代理服务器,这是SQUID的最基本功能:通过在squi ...

  7. Unity内存优化

    [Unity内存优化] 1.在Update方法或循环中,少用string类,因为string类的每次操作都会调用new生成新字符串对象.用StringBuilder代替string,StringBui ...

  8. glTexGen

    [glTexGen] Rather than having to explicitly provide a texture coordinate for each vertex, we can use ...

  9. MonoBehaviour.print和Debug.Log是同样的作用

    MonoBehaviour.print("identical------------------------");

  10. SpringBoot 中 使用Mybatis时 如果后端数据库为 Oracle注意事项

    报错信息如下: Could not set parameters for mapping: ParameterMapping{property='age', mode=IN, javaType=cla ...