使用System.Data.SQLite及其EF模块操作SQLite数据库(文件)
- SQLite for .NET (System.Data.SQLite)
- introduction
- An ADO.NET provider for SQLite including EF and Linq functions.
- http://system.data.sqlite.org/index.html/doc/trunk/www/index.wiki
- Developed by SQLite Development Team
- License: Public Domain, Open-Source, not Open-Contribution
- 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
- Add references (Nuget to find “System.Data.SQLite”)
在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数据库(文件)的更多相关文章
- Python使用cx_Oracle模块操作Oracle数据库--通过sql语句和存储操作
https://www.jb51.net/article/125160.htm?utm_medium=referral Python使用cx_Oracle调用Oracle存储过程的方法示例 http ...
- 【UWP】利用EF Core操作SQLite
在以往开发中,一定要在vs中安装SQLite for Universal App Platform以及一款wrapper,如SQLitePCL.现在有了EntitfyFramewrok Core,我们 ...
- python用sqlite3模块操作sqlite数据库-乾颐堂
SQLite是一个包含在C库中的轻量级数据库.它并不需要独立的维护进程,并且允许使用非标准变体(nonstandard variant)的SQL查询语句来访问数据库. 一些应用可是使用SQLite保存 ...
- ASP.NET Core使用EF Core操作MySql数据库
ASP.NET Core操作MySql数据库, 这样整套环境都可以布署在Linux上 使用微软的 Microsoft.EntityFrameworkCore(2.1.4) 和MySql出的 MySql ...
- 【SQLite】 C#中操作SQlite
简介 SQLite是轻量级数据库,具体的介绍请参考官网(SQLite官网).在WinForm的项目中需要采用独立的数据库访问,可在断网单机上使用,所以选择了SQLite! 使用 主要针对C#项目(Wi ...
- 以EF形式操作mysql数据库
1.引入Nuget包: 2.书写EF操作上下文 public class MySqlContext:DbContext { protected override void OnConfiguring( ...
- nodeJS中使用mongoose模块操作mongodb数据库
在实际运用中,对于数据库的操作我们不可能一直在cmd命令行中进行操作,一般情况下需要在node环境中来操作mongodb数据库,这时就需要引入mongoose模块来对数据库进行增删改查等操作. 首先, ...
- .Net版SQLite无法访问网络位置的数据库文件-winOpen,os_win.c 36702异常
最近一个C#小程序,希望将SQLite数据库放在网络共享的位置,让多个客户端同时访问.却发现SQLite连接不上该网络位置的数据库,而如果数据库在本地则一切正常. 例如将SQLite数据库 test. ...
- .net core使用ef core操作mysql数据库
新建.net core webapi项目 在NuGet包管理器中搜索 MySql.Data.EntityFrameworkCore并安装,安装的8.0.14版本,只安装这一个就够了 安装后创建Data ...
随机推荐
- views获取数据 -- request包含的方法
request.GET request.POST request.FILES request.path_info request.xxx.getlist request.method request. ...
- 常见的APP性能测试指标
性能测试在软件的质量保证中起着重要的作用,它包括的测试内容丰富多样.中国软件评测中心将性能测试概括为三个方面:应用在客户端性能的测试.应用在网络上性能的测试和应用在服务器端性能的测试.通常情况下,三方 ...
- 安装了Anaconda之后,Maya运行报错,Python 找不到 Maya 的 Python 模块
以前Maya用的好好地,结果安装了Anaconda之后,maya启动以后,日志就会报错(如下),只能自主建模,不能打开以前创建的模型,也不能导入fbx,错误提示就是Maya找不到Python模块,在网 ...
- Linux系统profile、bashrc、bash_profile等环境设置文件的使用
一.前言 关于bash的环境设置文件,分为系统设置和个人设置,一般来说建议用户直接修改个人的设置. 本文测试环境为:centos6.5. 二.系统设置值 1. /etc/sysconfig/i18n ...
- nginx相关教程
1.nginx简易的教程 http://www.cnblogs.com/jingmoxukong/p/5945200.html#%E8%B7%A8%E5%9F%9F%E8%A7%A3%E5%86%B3 ...
- 设计模式(java)--模版方法模式之任务分配
转自:http://blog.csdn.net/zhengzhb/article/details/7405608 定义:定义一个操作中算法的框架,而将一些步骤延迟到子类中,使得子类可以不改变算法的结构 ...
- JS中的唯一容器:数组
JS中的唯一容器:数组 一.什么类型的数据都可以存储 二. 定义的方式有两种 1 . var arra=[];var arra=[“a”,“b”,"c"]; 2.v ...
- transition与animation的区别
transition需要事件触发,animation可以直接自动触发,而且功能上更为强大,包括可以设置不同时间段的动画规则,还有状态的控制,事件等等.
- Go 笔记和疑问?
前言: 本文是学习<<go语言程序设计>> -- 清华大学出版社(王鹏 编著) 的2014年1月第一版 做的一些笔记 , 如有侵权, 请告知笔者, 将在24小时内删除, 转载请 ...
- 项目中遇到的死锁问题: Lock wait timeout exceeded; try restarting transaction
最近项目中频繁出现 Lock wait timeout exceeded; try restarting transaction这个错误,把我们弄得痛苦不堪啊,为了解决问题,上网上找好多资料,终于把 ...