问题描述:

Please check the Table below:

Scope is: I have to check in the database the top profileid and have to increase it by 1. If no data is there then it will fetch 0 and will increase it by 1.

I am getting the top value when there is data but in case the table is completely empty, I am getting exception. Code is as below.

 public Decimal GetTopProfileID()

{

Decimal topID = 0;

var profileID = _dbContext.tblProfile.Max(n => n.profileid);

try

{

if (profileID == null)

{

topID = 1;

}

else

{

topID = Convert.ToDecimal(profileID);

topID++;

}

}

catch (Exception)

{

throw;

}

return topID;

}

Please help me find the solution. Ready for any question.

Thanks in advance !!

网友答案:

When there's no record in the table and you try to get .Max() value, then it will throw an error, so its better to verify if any record exist or not.

Update your code as follows.

if (_dbContext.tblProfile.Any()) {
    //Verify records in tblProfile table, if there's any record exist or not

    return Convert.ToDecimal(_dbContext.tblProfile.Max(n = > n.profileid)) + 1;
    try {
        if (profileID == null) {
            topID = 1;
        } else {
            topID = Convert.ToDecimal(profileID);
            topID++;
        }
    } catch (Exception) {
        throw;
    }

    return topID;
} else { //If there's no value in table then assuming it should return 1.
    return 1;
}

Update

Or you can make it more simpler:

if (_dbContext.tblProfile.Any()) {
        //Verify records in tblProfile table, if there's any record exist or not

        return Convert.ToDecimal(_dbContext.tblProfile.Max(n = > n.profileid)) + 1;
    } else { //If there's no value in table then assuming it should return 1.
        return 1;
    }
网友答案:

You can use this code:

if (_dbContext.tblProfile.Any()) 
{
   //Verify records in tblProfile table, if there's any record exist or not
   var profileID = _dbContext.tblProfile.Max(n = > n.profileid) ?? 0;    

   return profileID + 1;
} 
else 
  return 1;

Also if ProfileID is not nullable then don't need care about null value.

Then you can use below code:

return _dbContext.tblProfile.Any() ? _dbContext.tblProfile.Max(n = > n.profileid) + 1 : 1;
网友答案:
          var profileID = _dbContext.tblProfile.OrderByDescending(n => n.profileid).FirstOrDefault();
  Decimal topID = 1;
                            if (profileID != null)
                            {
                             decimal.TryParse(profileID.ProfileId, out topID);
                             topID++;
                            }

                        return topID;
            }

Above answer by Moksh Shah is correct, but in that case we are hitting Data Base twice, I think this should produce the desired result.

网友答案:

Use LastOrDefault() like this:

decimal variableName = Convert.ToDecimal(_dbContext.tblProfile.Select(x=> x.ProfileId).LastOrDefault() + 1);

Should work.

This is better than other solution as there is only one database call.

相关阅读:
Top