【问题标题】:How to use different databases (SQL Server, Oracle) from the same ASP.NET Core C# code如何从相同的 ASP.NET Core C# 代码使用不同的数据库(SQL Server、Oracle)
【发布时间】:2019-07-13 10:42:31
【问题描述】:

我有执行基本 CRUD 操作的 C# 代码。我有一个定义为 AppDal 的类库,其中包含 Db 操作(用于 SQL Server),并且我在 C# 代码中使用命名空间。

如何使用相同的 c# 代码为另一个数据库(如 Oracle)执行数据库操作。我想在appsettings.json 中设置数据库名称。在此基础上,它将决定连接到哪个数据库。我将为另一个数据库(如 OracleDAL)创建另一个类库。

using AppDal; 

public IActionResult Add(CustomerModel input)
{
     ResponseModel response = new ResponseModel();

     Dal dal = new Dal();          
     int Id = dal.Add(input);

     if (Id > 0)
     {
         response.Id = Id;
         response.Message = "Record added successfully";
     }
     else
     {
         response.Message = "Record not added";
     }  

     return Json(response);
 }

 namespace AppDal
 {
      public int Add(CustomerModel input)
      {
            SqlParameter[] param = new SqlParameter[]
            {
                new SqlParameter("@Id",input.Id),
                new SqlParameter("@CompanyId",input.CompanyId),         
                new SqlParameter("@Title",input.Title),              
                new SqlParameter("@Address",input.Address),         
            };

            int result = SqlHelper.ExecuteScalar(SqlHelper.defaultDB, CommandType.Text, CustomerQueries.Add, param).ToInt();
            return result;
        } 
}

如果我创建另一个应用程序是可能的,但这会增加维护时间。我想使用相同的应用程序。

【问题讨论】:

    标签: c# asp.net asp.net-core asp.net-core-mvc


    【解决方案1】:

    解决此问题的一种方法是创建一个接口,例如 IDal,它将具有您所有的 CRUD 签名函数,然后创建一个继承 Sql Server 和 Oracle 的 IDal 的具体类。

    然后使用接口 IDal 作为 Dal 对象的声明类型。例如,

    IDal Dal = DalForSqlServer() 或 IDal Dal = DalForOracle();

    【讨论】:

      【解决方案2】:

      解决问题的最佳方法是使用 ORM,如 Entity Framework Core。您无需更改任何代码,只需更改实体框架提供程序。相同的代码适用于 SQL、MySql、Oracle、PostgreSQL、SQL Lite 等。

      几个链接可以帮助你:https://github.com/aspnet/EntityFrameworkCore
      EF 核心提供者:https://entityframework.net/supported-database-providers

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-03
        • 1970-01-01
        • 2020-01-17
        • 1970-01-01
        • 2017-08-25
        • 1970-01-01
        • 1970-01-01
        • 2013-03-09
        相关资源
        最近更新 更多