我有一个*.MDB数据库文件,我想知道是否有可能或建议在C#中使用LINQ来对付它.我也想知道一些简单的例子会是什么样子.
我对LINQ知之甚少,但我对此任务的要求非常简单(我相信).用户将传递给Microsoft Access MDB数据库的文件路径,我想使用LINQ将行添加到数据库中的一个表.
你想要的是LINQ to ODBC提供程序,或LINQ to JET/OLEDB提供程序.
开箱即用,MS没有制作一个.可能有第三方.
实际上我最近(今天)发现你可以使用LinqToSql访问Access数据库.它必须是2002或更新的格式,您将无法将表拖放到datacontext中,因此可以在dbml中手动创建对象,也可以使用SQL Server Migration for Access将其移动到sql server和然后拖放你想要的一切.当您想要实际创建上下文时,将其传递给OleDbConnection.在OleDbConnection上使用标准的Jet.OLEDB.4.0连接字符串,你很高兴.不确定这可能会产生的限制.我刚做了一个快速的样本并且没有问题就做了OrderBy.
我写了一个小样本程序来测试David的回答.您需要创建一个访问数据库并手动创建Linq-to-SQL的DBML,因为您无法拖放它们.
插入失败,引用Missing semicolon (;) at end of SQL statement.
但查询似乎正常.
using System; using System.Collections.Generic; using System.Data.OleDb; using System.IO; using System.Linq; using Linq2Access.Data; namespace Linq2Access { class Program { static readonly string AppPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); static readonly string DbPath = Path.Combine(AppPath, "Data", "database.accdb"); static readonly string DbConnString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + DbPath + "';Persist Security Info=False;"; static void Main(string[] args) { if (!File.Exists(DbPath)) throw new Exception("Database file does not exist!"); using (OleDbConnection connection = new OleDbConnection(DbConnString)) using (DataRepositoryDataContext db = new DataRepositoryDataContext(connection)) { Listprojects = new List (); for (int i = 1; i <= 10; i++) { dbProject p = new dbProject() { Title = "Project #" + i }; for (int j = 1; j <= 10; j++) { dbTask t = new dbTask() { Title = "Task #" + (i * j) }; p.dbTasks.Add(t); } projects.Add(p); } try { //This will fail to submit db.dbProjects.InsertAllOnSubmit(projects); db.SubmitChanges(); Console.WriteLine("Write succeeded! {0} projects, {1} tasks inserted", projects.Count, projects.Sum(x => x.dbTasks.Count)); } catch(Exception ex) { Console.WriteLine("Write FAILED. Details:"); Console.WriteLine(ex); Console.WriteLine(); } try { //However, if you create the items manually in Access they seem to query fine var projectsFromDb = db.dbProjects.Where(x => x.Title.Contains("#1")) .OrderBy(x => x.ProjectID) .ToList(); Console.WriteLine("Query succeeded! {0} Projects, {1} Tasks", projectsFromDb.Count, projectsFromDb.Sum(x => x.dbTasks.Count)); } catch (Exception ex) { Console.WriteLine("Query FAILED. Details:"); Console.WriteLine(ex); Console.WriteLine(); } Console.WriteLine(); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } } } }