NullReferenceException 包含 LINQ 表达式 MVC3
Details.cshtml 页面中的以下代码:
@{
@Html.Raw(" | ");
for (int i = 0; i < Model.Payments.Count; i++)
{
@Html.Raw("<a href=../../Payment/Details/" + Model.ID + "/" + Model.Payments.ElementAt(i).accountID + ">" + Model.Payments.ElementAt(i).Account.landIOC + "</a>");
@Html.Raw(" | ");
}
}
Model.Payments.ElementAt(i).Account 由于某种原因始终为 NULL,尽管一笔付款始终只有一个帐户并且我们在 LINQ 表达式 (PaymentController) 中包含 Account:
_erasDb.Payments.Include("Account").Include("Event").Where(...)
我们不知道为什么帐户为空。完整代码请参见:
Following code in a Details.cshtml page:
@{
@Html.Raw(" | ");
for (int i = 0; i < Model.Payments.Count; i++)
{
@Html.Raw("<a href=../../Payment/Details/" + Model.ID + "/" + Model.Payments.ElementAt(i).accountID + ">" + Model.Payments.ElementAt(i).Account.landIOC + "</a>");
@Html.Raw(" | ");
}
}
Model.Payments.ElementAt(i).Account is always NULL for some reason, although a payment always has exactly one account AND we include Account in our LINQ expression (PaymentController):
_erasDb.Payments.Include("Account").Include("Event").Where(...)
We have no idea why Account is NULL. For the complete code, see:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
多次调用
ElementAt
效率非常低。只需切换到foreach
- 它应该修复ElementAt
返回null
的问题,更高效、更简单。另外,为什么不只是:
如果您使用大量
@Html.Raw(...)
,您可能错过了一个技巧...特别是,您很有可能打开 xss如果使用太多.Raw
,就会出现漏洞。Multiple calls to
ElementAt
is pretty inefficient. Just switch toforeach
- it should fixElementAt
returningnull
, be more efficient, and simpler.Also, why not just:
If you are using lots of
@Html.Raw(...)
, you're probably missing a trick... in particular, you stand a good chance of opening xss holes if you use too much.Raw
.问题:您首先使用数据库、模型还是代码的 EF 方案?
在您看来,您可以使用
; |
替换 Html.Raw(" | ");同样,您的链接生成策略有点固定。我想这些链接有相应的操作,因此必须有路由,您可以使用 Html.ActionLink。
使用 foreach(var m in Model.Payments) 进行迭代可以使您的代码更加漂亮:
现在这可能是一个起点。
Questions: what EF scheme are you using db, model or code first?
in your view you can use
<text> | </text>
to replace Html.Raw(" | ");Again your link generation strategy is a bit wired. Those links, i suppose, have corresponding actions, so there must be routes and you can use Html.ActionLink.
And iterating with a foreach(var m in Model.Payments) could make your code a bit more prety:
Now this could be a starting point.