【问题标题】:how to call stored procedure from database independent application c# , codefirst如何从独立于数据库的应用程序c#,codefirst调用存储过程
【发布时间】:2017-05-19 21:03:15
【问题描述】:

我为我的应用程序支持的每种数据库类型创建了过程。并添加到他们的迁移文件中。

我可以在我的代码优先应用程序中调用这两种类型的存储过程 MSSQL 一个

worker.StoredProcedures.ExecuteWithStoreProcedure("sp_userVirman @ResourceUserID,@targetUserID", 
new SqlParameter("ResourceUserID",DbType.Int64) { Value = 1 },
 new SqlParameter("targetUserID", DbType.Int64) { Value = 2 });

两个

worker.StoredProcedures.ExecuteWithStoreProcedure(string.Format("sp_userVirman {0},{1}", 1, 2));

但是当 db 提供程序更改为 mysql 时,它会出错。

EntityFramework.dll 中出现“MySql.Data.MySqlClient.MySqlException”类型的未处理异常 附加信息:只能存储 MySqlParameter 对象

供应商也可以更改 oracle postgresql mysql 等。

如何解决这个问题?

我不想使用 if provider== mssql if provider==mysql etc...

这是我的主要功能

 public void ExecuteWithStoreProcedure(string query, params object[] parameters)
    {
        _dbContext.Database.ExecuteSqlCommand(query, parameters);
    }

【问题讨论】:

    标签: mysql sql-server database stored-procedures database-independent


    【解决方案1】:

    这是我能找到的最佳用途。没有 switch case 或者 if else 是没有办法的

    public void sp_uservirman(Nullable<int> resourceUserID, Nullable<int> targetUserID)
        {
            switch (GlobalData.CustomerDataSourceType)
            {
                case ContextFactory.DataSourceTypes.None:
                    break;
                case ContextFactory.DataSourceTypes.MSSQL:
                    SqlParameter param= new SqlParameter("@resourceuserıd",resourceUserID);
                    SqlParameter param1= new SqlParameter("@targetUserID",targetUserID);
                    _dbContext.Database.ExecuteSqlCommand("sp_uservirman  @resourceuserıd,@targetUserID", param, param1);
                    break;
                case ContextFactory.DataSourceTypes.MySQL:
    
                    MySqlParameter param3 = new MySqlParameter("@resourceuserıd", resourceUserID);
                    MySqlParameter param4 = new MySqlParameter("@targetUserID", targetUserID);
    
    
                    _dbContext.Database.ExecuteSqlCommand("CALL sp_uservirman  (@resourceuserıd,@targetUserID)", param3, param4);
                    break;
                case ContextFactory.DataSourceTypes.ORACLE:
    
                    string query = string.Format("BEGIN SP_USERVIRMAN ({0},{1}) ; END;", resourceUserID, targetUserID);
                    _dbContext.Database.ExecuteSqlCommand(query);
    
                    break;
                default:
                    break;
            }
    
        }
    

    用法:

     worker.StoredProcedures.sp_uservirman(1, 2);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-06
      • 1970-01-01
      • 2017-06-12
      • 2019-07-24
      相关资源
      最近更新 更多