gpt4 book ai didi

c# - 错误: The cast to value type 'System.Int32' failed because the materialized value is null

转载 作者:行者123 更新时间:2023-12-02 10:52:05 27 4
gpt4 key购买 nike

我遇到了问题

The cast to value type 'System.Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.

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

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

我的 Controller :

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

错误发生在变量lastTransactionId上。

最佳答案

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

关于c# - 错误: The cast to value type 'System.Int32' failed because the materialized value is null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36124113/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com