gpt4 book ai didi

c# - EF 和存储过程返回动态结果

转载 作者:太空宇宙 更新时间:2023-11-03 13:26:20 26 4
gpt4 key购买 nike

我有一个存储过程,其输入定义了返回的列。

如何遍历结果?

我试过类似的解决方案:

var selectColsParam = new System.Data.SqlClient.SqlParameter()
{
ParameterName = "@SelectCols",
Value = "Person.FirstName",
};
string sql = string.Format("dbo.DynamicResultSP {0} ", selectColsParam.ParameterName);

var result = db.Database.SqlQuery<List<dynamic>>(sql, selectColsParam);

充其量,“结果”包含我可以迭代的正确行数,但“行”本身只是一个我似乎无能为力的对象。

我不需要知道列名,但需要能够遍历字段。

我知道有一个根据输入返回不同列的存储过程被认为不是好的设计,但是,这是我必须使用的,因此更改 SP 不是一个选项。

感谢任何帮助

最佳答案

我今天遇到了同样的问题,不得不求助于 SqlCommand 而不是直接使用对象上下文。

    // Retrieve the connection from the object context
var entityConnection = this.ObjectContext.GetConnection() as EntityConnection;
var dbConnection = entityConnection.StoreConnection as SqlConnection;

// Create the command and associated parameters (dynamically passed in perhaps)
var command = new SqlCommand("dbo.DynamicResultSP");
command.Parameters.AddWithValue("@SelectCols", "Person.FirstName");
////command.Parameters.AddWithValue("@AnotherParameter", "Parameter.SecondValue");
////command.Parameters.AddWithValue("@AThirdParameter", "YetAnotherValue");

dbConnection.Open();
using (var reader = command.ExecuteReader())
{
// Get the column names
columnNames = new string[reader.FieldCount];
for (int i = 0; i < reader.FieldCount; i++)
{
columnNames[i] = reader.GetName(i);
}

// Get the actual results
while (reader.Read())
{
var result = new string[reader.FieldCount];
for (int i = 0; i < reader.FieldCount; i++)
{
result[i] = reader[i].ToString();
}

results.Add(result);
}
}
dbConnection.Close();

现在您应该可以访问字段名称和结果。

虽然这不是最漂亮的解决方案,但它可以完成工作。欢迎提出建议。

关于c# - EF 和存储过程返回动态结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22315003/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com