【发布时间】:2021-10-28 21:50:28
【问题描述】:
我有以下模型类:
[key]
public int CustomerId { get; set; }
public string CustomerName { get; set; }
[ForeignKey("CustomerType")]
public int? CustomerTypeId { get; set; }
public virtual CustomerType CustomerType { get; set; }
[Key]
public int CustomerTypeId { get; set; }
public string CustomerTypeCode { get; set; }
然后我想用这个控制器代码将它加载到一个视图中:
public async Task<IActionResult> Index()
{
var obj = _db.Customer.Include(i => i.CustomerType);
return View(await obj.ToListAsync());
}
在观点上:
@using IEnumerable<myProject.Models.Customer>
<table>
<thead>
<tr>
<th>Customer
<th>CustomerType
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@item.Customer</td>
<td>@item.CustomerType.Code</td>
</tr>
}
</tbody>
</table>
当我尝试运行它时,我收到@item.CustomerType.Code 的错误,因为数据库中的数据为空:
System.NullReferenceException: '对象引用未设置为对象的实例。'
有人知道为什么吗?即使我尝试将? 放在模型上,它也不起作用。
非常感谢。
【问题讨论】:
-
根据您的代码,来自
Customer的一些记录可能没有CustomerType。这就是你的情况:item.CustomerType是null。添加检查null或定义public int CustomerTypeId { get; set; }取决于您的数据设计。 -
那么您对空数据的期望处理是什么,或者不将空数据绑定到表中?你想要哪一个?
-
@Jackdaw 是的,有些客户将没有 CustomerType。我在模型中输入了
?。但同样,它出现了错误。我该如何处理? -
@MdFaridUddinKiron,我想处理空数据。所以它会在视图上空白。
-
谢谢你的回复很酷,请稍等
标签: c# entity-framework asp.net-core razor-pages