Get output parameter value of a stored procedure using EF Core?

后端 未结 4 1584
终归单人心
终归单人心 2020-12-21 01:12

I am using Asp.net core and EF core in my application. Basically I want to get multiple result set from a single stored procedure. Tried to search it for last 2 days no such

4条回答
  •  天涯浪人
    2020-12-21 01:41

    In EF Core you can't return ad-hoc types from raw SQL queries yet (they are working on this), so you will need a workaround for this issue. Add this class to your project:

    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Infrastructure;
    using Microsoft.EntityFrameworkCore.Internal;
    using Microsoft.EntityFrameworkCore.Storage;
    using Microsoft.Extensions.DependencyInjection;
    using System;
    using System.Collections.Generic;
    using System.Data.Common;
    using System.Linq;
    using System.Reflection;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace Microsoft.EntityFrameworkCore
    {
    
        public static class RDFacadeExtensions
        {
            public static RelationalDataReader ExecuteSqlQuery(this DatabaseFacade databaseFacade, string sql, params object[] parameters)
            {
                var concurrencyDetector = databaseFacade.GetService();
    
                using (concurrencyDetector.EnterCriticalSection())
                {
                    var rawSqlCommand = databaseFacade
                        .GetService()
                        .Build(sql, parameters);
    
                    return rawSqlCommand
                        .RelationalCommand
                        .ExecuteReader(
                            databaseFacade.GetService(),
                            parameterValues: rawSqlCommand.ParameterValues);
                }
            }
        }
    }
    

    Then you can call the method below and get the OUTPUT from you SP, here's a sample:

                var _sMsg = new SqlParameter("sMsg", "")
                {
                    Direction = ParameterDirection.Output,
                    DbType = DbType.String,
                    Size = 500
                };
    
                var sql = "exec sp_foo @sUserId, @sMsg OUTPUT";
    
                using (var dr = _ctx.Database.ExecuteSqlQuery(sql, _sUserID, _sMsg))
                {
                    //here you can retrive your table
                    while (dr.DbDataReader.Read())
                    {
                        var bar = dr.DbDataReader[0].ToString();
                    }
    
                    //here is your OUTPUT
                    return _sMsg.Value.ToString();
                }
    

提交回复
热议问题