我不确定这是否可能。我可能正在尝试使用错误的工具来完成我正在尝试做的工作。
假设我想做以下事情:
我执行一个名为“GetTableName”的函数,它返回我想从中获取数据的 SQL 表的名称。
我执行另一个名为“GetFields”的函数,它返回 SQL 表中一个或多个字段的名称。
我希望能够编写另一个函数,该函数将返回一个 DataSet(或其他一些通用对象),其中包含“GetTableName”指定的表中的行以及“GetFields”指定的字段
我知道我可以使用旧的 ADO.net 界面来执行此操作,但是是否有合适的方法来使用 Entity Framework 来执行此操作?
要强调的是,代码不会在编译时知道从 SQL 返回的数据的形状。
最佳答案
按照规则,您不应在 EF 应用程序中使用数据集。但是,如果您确实需要(例如,提供报告),该解决方案应该有效(它是 EF 6 代码):
DataSet GetDataSet(string sql, CommandType commandType, Dictionary<string, Object> parameters)
{
// creates resulting dataset
var result = new DataSet();
// creates a data access context (DbContext descendant)
using (var context = new MyDbContext())
{
// creates a Command
var cmd = context.Database.Connection.CreateCommand();
cmd.CommandType = commandType;
cmd.CommandText = sql;
// adds all parameters
foreach (var pr in parameters)
{
var p = cmd.CreateParameter();
p.ParameterName = pr.Key;
p.Value = pr.Value;
cmd.Parameters.Add(p);
}
try
{
// executes
context.Database.Connection.Open();
var reader = cmd.ExecuteReader();
// loop through all resultsets (considering that it's possible to have more than one)
do
{
// loads the DataTable (schema will be fetch automatically)
var tb = new DataTable();
tb.Load(reader);
result.Tables.Add(tb);
} while (!reader.IsClosed);
}
finally
{
// closes the connection
context.Database.Connection.Close();
}
}
// returns the DataSet
return result;
}
关于.net - 如何在 Entity Framework 5.0 中获取数据集作为查询结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17686255/