简体   繁体   中英

Can't handle if reader.ReadDataTable() doesn't return any DATA from stored procedure in database

I have created an API called GetCustomerPrivacyStatus , it is trying to find out the 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;
}

In the GetTermsAndConditionstatus it is calling a stored procedure, if the orgId is new that means it is not present is the database, that's why dataTable.Rows[0]["TermsAndConditionAccepted"] is throwing an error

There is no row at position 0

I am not able to able to think how to resolve this situation.

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;
    }
}

Stored procedure is:

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

Is there is any way if there is no rows the result variable should be set to null?

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;

That should fix your problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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