You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用DbContext调用存储过程填充DataTable时数据丢失问题求助

DbContext调用存储过程填充DataTable时数据丢失问题求助

大家好,我碰到一个特别头疼的问题:我有一个逻辑很复杂的存储过程,单独执行它明明能返回数据,但用DbContext调用并尝试把结果加载到DataTable里的时候,数据却莫名其妙“消失”了。

下面是我写的代码,麻烦各位帮忙排查下问题所在:

using (var dbContext = new SuperPortalDbContext())
{
    // Create resulting data table
    System.Data.DataTable result = new DataTable();

    // Create command
    var cmd = dbContext.Database.Connection.CreateCommand();
    cmd.CommandType = commandType;
    cmd.CommandText = sql;
    cmd.CommandTimeout = 120;

    // Add all parameters
    foreach (SqlParameter parameter in parameters)
    {
        var p = cmd.CreateParameter();
        p.ParameterName = parameter.ParameterName;
        p.Value = parameter.Value;
        cmd.Parameters.Add(p);
    }

    try
    {
        // Execute
        dbContext.Database.Connection.Open();
        System.Data.Common.DbDataReader reader = cmd.ExecuteReader();
        result.Load(reader);
    }
    finally
    {
        // closes the connection
        dbContext.Database.Connection.Close();
    }

    // returns the DataSet
    return result;
}

我确认存储本身是能返回结果的,但这段代码执行后DataTable始终是空的,实在摸不着头绪,有没有大佬能给我指个方向?

备注:内容来源于stack exchange,提问作者Tom Akerman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.23 09:09:12