";对象引用未设置为对象的实例";嵌套列出ASP.NET MVC LINQ实体框架
本文关键字:quot ASP NET LINQ 框架 实体 MVC 实例 对象引用 设置 对象 | 更新日期: 2023-09-27 18:25:51
正如标题所说,我在试图从要显示的用户对象中获取值时遇到了这个错误。我使用实体框架代码优先,所以所有的模型都是生成的,我试图将多个表相互组合。"显示所有用户的项目数据和弹性工作时间"(现在弹性工作时间只是小数)
型号:
public class ListModel
{
public List<StaffModel> StaffModelList { get; set; }
}
public class StaffModel
{
public FlexModel Flex { get; set; }
public List<string> ProjectName { get; set; }
}
public class FlexModel
{
public User User { get; set; }
public decimal FlexTime { get; set; }
}
视图:
@model Aviato.ViewModel.ListModel
<table class="table">
@foreach (var item in Model.StaffModelList)
{
<tr>
<td>@item.Flex.User.UserId</td>
<td>@item.Flex.FlexTime</td>
<td>@item.ProjectName</td>
<td>@item.Flex.User.SocialSecurityNumber</td>
<td>@item.Flex.User.FirstName</td>
<td>@item.Flex.User.LastName</td>
<td>@item.Flex.User.Address1</td>
<td>@item.Flex.User.ZipCode</td>
<td>@item.Flex.User.City</td>
<td>@item.Flex.User.PhoneNumber1</td>
<td>@item.Flex.User.EmploymentStartDate</td>
<td>@item.Flex.User.Password</td>
@foreach (var project in item.ProjectName)
{
<td>@project</td>
}
@Html.ActionLink("Redigera", "Edit", new { id = item.Flex.User.UserId })
@Html.ActionLink("Ta bort", "Delete", new { id = item.Flex.User.UserId })
</tr>
}
</table>
控制器:
private readonly AviatoModel _db = new AviatoModel(); //Database
public ActionResult Index()
{
var projects = _db.Projects.ToList();
var users = _db.Users.ToList();
var model = new ListModel();
model.StaffModelList = new List<StaffModel>();
foreach (var u in users)
{
var flexModel = new StaffModel();
flexModel.Flex.User = u; //This is where the Error occurs.
flexModel.Flex.FlexTime = GetFlex.Flex(u.UserId);
model.StaffModelList.Add(flexModel);
}
return View(model);
}
请帮忙。
StaffModel
的Flex
属性从未实例化,因此当您尝试访问其上的方法时,您会得到NullReferenceException
。向类中添加一个构造函数,将其创建为空对象:
public class StaffModel
{
public StaffModel()
{
Flex = new FlexModel();
}
//snip
}