错误:强制转换为值类型'System.Int32'失败,因为具体化值为 null



我遇到了问题

强制转换为值类型"System.Int32"失败,因为具体化值为 null。结果类型的泛型参数或查询必须使用可为 null 的类型。

我已经查找了可以解决我遇到的问题的答案,但找不到类似的情况。

我正在尝试从account id作为输入中找出tblTransactions中的max交易 ID。如果帐户没有任何交易,则会导致错误。这两个表之间的关系为 tblTransaction。 accountId = tblAccount.Id

我的控制器:

//GET: Balance
    [Authorize]
    public ActionResult Index()
    {
        string useracc = (string)Session["AccountNumber"];
        var accountInstance = db.Accounts.FirstOrDefault(w => w.AccountNumber.ToString() == useracc);

        List<Transaction> AccountTransactions = db.Transactions.Where(w => w.AccountId == accountInstance.Id&&w.IsCancelled ==false).Select(w => w).OrderByDescending(w => w.Date).ToList();
            var accountStatement = AccountTransactions.Where(w => w.TransactionTypeId == 2 && w.Date.Year >= 2015).OrderByDescending(w => w.Date).ToList();
            var lastTransactionId = db.Transactions.Where(w => w.AccountId == accountInstance.Id && w.IsCancelled == false && w.TransactionTypeId == 2 && w.Date.Year >= 2015).Max(t => t.Id);
            var needDueDate = db.SystemInvoices.Where(s => s.Id == lastTransactionId).Select(s => s.DueDate).FirstOrDefault();

            List<customBalanceInfoItem> currCustomBalance = new List<customBalanceInfoItem>();
            customBalanceInfoItem displayItem = new customBalanceInfoItem();
            displayItem.AccountNumber = accountInstance.AccountNumber;
            displayItem.DueDate = needDueDate;
            currCustomBalance.Add(displayItem);
            return View(currCustomBalance);
        }

错误发生在 var lastTransactionId 上。

使用 DefaultIfEmpty() 修改它,检查这里

修改后的查询

var lastTransactionId = db.Transactions.Where(w => w.AccountId == accountInstance.Id && w.IsCancelled == false && w.TransactionTypeId == 2 && w.Date.Year >= 2015)
                                       .Select(t=>t.Id)
                                       .DefaultIfEmpty(-1)
                                       .Max()

你可以定义需要返回的值,如果集合是空的,就像我把它做成-1一样,否则它将是默认值

尝试添加第一个或默认值,以防止空异常

var lastTransactionId = db.Transactions.Where(w => w.AccountId == accountInstance.Id && w.IsCancelled == false && w.TransactionTypeId == 2 && w.Date.Year >= 2015).Max(t => t.Id).FirstOrDefault();

最新更新