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

时间:2016-03-21 06:01:04

标签: c# asp.net-mvc entity-framework linq

我遇到了问题

  

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

我已经找到了解决问题的答案,但找不到相似的案例。

我正在尝试从max中找出tblTransactions中的account id交易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发生错误。

2 个答案:

答案 0 :(得分:6)

使用DefaultIfEmpty()进行修改,然后选中here

修改后的查询

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,否则它将是默认值

答案 1 :(得分:-1)

尝试添加first或default,以防止出现null异常

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();
相关问题