C#自動註冊sqlite ado.net資料庫驅動 及 自訂連接字串

來源:互聯網
上載者:User

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;

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.