【问题标题】:Can't handle if reader.ReadDataTable() doesn't return any DATA from stored procedure in database如果 reader.ReadDataTable() 没有从数据库中的存储过程返回任何数据,则无法处理
【发布时间】:2021-01-29 18:54:55
【问题描述】:

我创建了一个名为 GetCustomerPrivacyStatus 的 API,它正在尝试找出 TandCstatus。

[HttpGet]
[Route("GetCustomerPrivacyStatus")]
public async Task<EULAInfo> GetCustomerPrivacyStatus()
{
    var result = new EULAInfo();

    string userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
    var orgId = await GetOrgIdOfUser().ConfigureAwait(false);
    var TandCvalue = MasterDatabase.GetTermsAndConditionstatus(orgId).ToString();
    var TandCInt = TandCvalue != null ? TandCvalue : "0";
    var TandCstatus = Int16.Parse(TandCInt) == 0 ? false : true;
        
    result.status = TandCstatus;
        
    return result;
}

GetTermsAndConditionstatus 中它正在调用存储过程,如果orgId 是新的,则意味着它不存在是数据库,这就是dataTable.Rows[0]["TermsAndConditionAccepted"] 抛出错误的原因

位置0没有行

我无法思考如何解决这种情况。

public object GetTermsAndConditionstatus(string orgId)
{
    using (var reader = new StoredProcedureReader(this, "GetTermsAndConditionstatus", new { orgId }))
    {
        var dataTable = reader.ReadDataTable();
        var result = dataTable.Rows[0]["TermsAndConditionAccepted"] ;
            
        return result;
    }
}

存储过程是:

CREATE PROCEDURE [dbo].[GetTermsAndConditionstatus]
    @orgId VARCHAR(100)
AS
    SELECT TermsAndConditionAccepted 
    FROM TermsAndConditionCheck 
    WHERE OrgId = @orgId

如果没有行,结果变量应该设置为空,有什么办法吗?

【问题讨论】:

  • 欢迎来到stackoverflow!不确定StoredProcedureReader 在调用存储过程时做了什么。这可能有助于使用使用 sql 数据适配器 stackoverflow.com/questions/1344697/…
  • @coder_b : StoredProcedureReader 是一种读取存储在数据库中的存储过程,在这种特定情况下,它调用 GetTermsAndConditionstatus 存储过程并将 orgId 作为参数传递
  • 你可以检查的东西很少,OrgId似乎是varchar,在你的sql中看起来它被用作int类型,另一件事是如果OrgId是一个需要换成单引号的字符串.最后确保您传递的 OrgId 存在于 TermsAndConditionCheck 表行中。

标签: c# asp.net .net database


【解决方案1】:
object result = null;

using (var reader = new StoredProcedureReader(this, "GetTermsAndConditionstatus", new { orgId }))
{
    var dataTable = reader.ReadDataTable();
   
    if (dataTable.Rows.Count > 0)
        result = dataTable.Rows[0]["TermsAndConditionAccepted"];   
}

return result;

这应该可以解决您的问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 2018-11-04
    • 2014-05-14
    相关资源
    最近更新 更多