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;