简体   繁体   English

如何执行在 EF 6 中返回可变列数的存储过程

[英]How to execute a stored procedure that returns variable number of columns in EF 6

Is there any way I can execute a stored procedure using EF 6 that can somehow handle variable number of columns returned?有什么方法可以使用 EF 6 执行存储过程,它可以以某种方式处理可变数量的返回列? I am doing a dynamic pivot in the stored procedure (converting row values to columns) and so, the number of columns returned varies based on an input id to the procedure.我在存储过程中执行动态 pivot(将行值转换为列),因此,返回的列数根据过程的输入 ID 而变化。 So, it is not known at compile time for me to declare properties in strongly typed POCO classes.因此,在编译时我不知道在强类型 POCO 类中声明属性。

I also tried using other constructors of SqlQuery and I just couldn't figure out how to get the results back.我还尝试使用SqlQuery的其他构造函数,但我只是不知道如何取回结果。

Thanks谢谢

I finally did this.我终于做到了。

var param = new SqlParameter[] {
    new SqlParameter() {
        ParameterName = "ID",
        SqlDbType =  System.Data.SqlDbType.BigInt,
        Direction = System.Data.ParameterDirection.Input,
        Value = someid
    }};
    
var context = new SystemDBContext();

using (var cnn = context.Database.Connection)
{
    var cmm = cnn.CreateCommand();
    cmm.CommandType = System.Data.CommandType.StoredProcedure;
    cmm.CommandText = "[dbo].[SPName]";
    cmm.Parameters.AddRange(param);
    cmm.Connection = cnn;
    cnn.Open();
    var reader = cmm.ExecuteReader();

    var list = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToList();
    int colCount = reader.FieldCount;

    while (reader.Read())
    {   
        for (var counter = 0; counter <colCount; counter++)
        {
            //do whatever`
        }           
    }       
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM