Linq 应用比较多的是直接连接SqlServer 数据库,然后建立*.dbml 文件,调用DataContext 来增删改查。
但其实Linq 其实也可以连接OleDbConnection
Linq 连接Access数据库,还需借助OleDbConnection ,下面是提供的DataContext 访问类
public class LinqConextClass:IDisposable
{
private OleDbConnection oleConnection;
private bool flagOpen=false;
private DataContext context;
public LinqConextClass()
{
oleConnection = new OleDbConnection(PubConstant.ConnectionString);
}
/// <summary>
/// 获取执行的上下文
/// </summary>
public DataContext Context
{
get
{
if (oleConnection != null && oleConnection.State == ConnectionState.Open && flagOpen)
{
context = new DataContext(oleConnection);
return context;
}
else
{
throw new Exception("打开数据库连接失败!");
return null;
}
}
}
public void Open()
{
if (oleConnection != null)
{
oleConnection.Open();
flagOpen = true;
}
}
public void Close()
{
if (oleConnection != null)
{
oleConnection.Close();
flagOpen = false;
}
}
#region IDisposable 成员
public void Dispose()
{
if (oleConnection != null)
{
oleConnection.Close();
oleConnection.Dispose();
}
if (context != null)
{
context.Connection.Close();
context.Dispose();
}
}
#endregion
}
{
private OleDbConnection oleConnection;
private bool flagOpen=false;
private DataContext context;
public LinqConextClass()
{
oleConnection = new OleDbConnection(PubConstant.ConnectionString);
}
/// <summary>
/// 获取执行的上下文
/// </summary>
public DataContext Context
{
get
{
if (oleConnection != null && oleConnection.State == ConnectionState.Open && flagOpen)
{
context = new DataContext(oleConnection);
return context;
}
else
{
throw new Exception("打开数据库连接失败!");
return null;
}
}
}
public void Open()
{
if (oleConnection != null)
{
oleConnection.Open();
flagOpen = true;
}
}
public void Close()
{
if (oleConnection != null)
{
oleConnection.Close();
flagOpen = false;
}
}
#region IDisposable 成员
public void Dispose()
{
if (oleConnection != null)
{
oleConnection.Close();
oleConnection.Dispose();
}
if (context != null)
{
context.Connection.Close();
context.Dispose();
}
}
#endregion
}