在不使用ORM的情况下,在c#中创建独立于供应商的dal的最佳方法是什么



目前我有一个项目涉及两个数据库提供商:

  1. SqlClient
  2. OleDb

我需要创建一个DAL来处理这些提供商。我想创建一个这样的界面:

public interface IDataAccessLayer
{
    public string GetSomeData();
}

并单独实现(尽管很简单,但这是错误的方式)

public class SqlClientDal : IDataAccessLayer
{
    public string GetSomeData() { }
}
public class OleDbDal : IDataAccessLayer
{
    public string GetSomeData() { }
}

我读过这样的帖子:

.Net:如何创建独立于供应商的数据集、表适配器、绑定(DB在运行时决定)(这很好,但没有提供任何示例)

获取DbProviderFactory

创建数据访问层(C#)(非常好,但表适配器依赖于供应商)

我想创建一个具有以下功能的DAL:

  1. 使用键入的数据表(使用visual studio设计器)
  2. 使用独立于供应商的数据适配器(手动创建)
  3. 非ORM

如何创建具有这些功能的简单DAL?

研究从以下类派生类:

System.Data.Common.DbConnection BaseConnection;
System.Data.Common.DbDataAdapter BaseAdapter;
namespace DAL
{
    public class DataAccess : DbConnection
    {
        protected override DbTransaction BeginDbTransaction(System.Data.IsolationLevel isolationLevel)
        {
            throw new Exception("The method or operation is not implemented.");
        }
        public override void ChangeDatabase(string databaseName)
        {
            throw new Exception("The method or operation is not implemented.");
        }
        public override void Close()
        {
            throw new Exception("The method or operation is not implemented.");
        }
        public override string ConnectionString
        {
            get
            {
                throw new Exception("The method or operation is not implemented.");
            }
            set
            {
                throw new Exception("The method or operation is not implemented.");
            }
        }
        protected override DbCommand CreateDbCommand()
        {
            throw new Exception("The method or operation is not implemented.");
        }
        public override string DataSource
        {
            get { throw new Exception("The method or operation is not implemented."); }
        }
        public override string Database
        {
            get { throw new Exception("The method or operation is not implemented."); }
        }
        public override void Open()
        {
            throw new Exception("The method or operation is not implemented.");
        }
        public override string ServerVersion
        {
            get { throw new Exception("The method or operation is not implemented."); }
        }
        public override System.Data.ConnectionState State
        {
            get { throw new Exception("The method or operation is not implemented."); }
        }
    }
}

乱处理这些函数和类中的每一个。它非常灵活。

请参阅我的答案编写任何数据库支持的通用驱动程序类。除非您在编写自己的DbAL时有非常特殊的需求,否则我建议您使用Micro ORM,如Dapper、FluentData或SqlFu。易用性(根据我的说法)是这些结构引人注目的地方。

最新更新