C#自动注册sqlite ado.net数据库驱动 及 自定义连接字符串

vista或以上系统必须取得系统管理员权限执行以下代码。sqlite.net使用了1.0.66.0,支持ado.net EF数据模型,下载地址:http://sourceforge.net/projects/sqlite-dotnet2/files/SQLite%20for%20ADO.NET%202.0/

部署时必须确保System.Data.SQLite.dll和System.Data.SQLite.Linq.dll都在项目的输入目录。即你的程序exe文件所在目录。

using System.Configuration;
using System.Xml.Linq;
using System.EnterpriseServices.Internal;

var d = ConfigurationManager.OpenMachineConfiguration().FilePath;
XElement xe = XElement.Load(d);
var dd = xe.Element("system.data").Element("DbProviderFactories").Elements("add");
if (dd.Where(md => md.Attribute("name").Value.Equals("SQLite Data Provider")).Count() == 0)
{
    Publish objPub = new Publish();
    objPub.GacRemove("System.Data.SQLite.dll");
    objPub.GacRemove("System.Data.SQLite.Linq.dll");
    objPub.GacInstall("System.Data.SQLite.dll");
    objPub.GacInstall("System.Data.SQLite.Linq.dll");

    xe.Element("system.data").Element("DbProviderFactories").Add(new XElement("add",
        new XAttribute("name", "SQLite Data Provider"), new XAttribute("invariant",
        "System.Data.SQLite"), new XAttribute("description", ".Net Framework Data Provider for SQLite"),
        new XAttribute("type", "System.Data.SQLite.SQLiteFactory, System.Data.SQLite, Version=1.0.66.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139")
        ));
    xe.Save(d);
}

以下顺便提供一个自定义ado.net EF的自定义数据库连接方法:

public EntityConnection GetEntityConnection()
{
    EntityConnectionStringBuilder ecsb = new EntityConnectionStringBuilder();
    ecsb.Metadata = string.Format(@"res://*/{0}.csdl|res://*/{0}.ssdl|res://*/{0}.msl", "Model1");
    ecsb.Provider = "System.Data.SQLite";
    ecsb.ProviderConnectionString = @"data source=data.db;Password=admin";
    EntityConnection ec = new EntityConnection(ecsb.ToString());
    return ec;
}

使用时:

dataEntities de = new dataEntities(GetEntityConnection());
dataGrid1.ItemsSource = de.userTable;

posted @   黎东海  阅读(626)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示