2014-10-07 46 views
-1

正如標題所示,當試圖從要顯示的用戶對象中獲取值時,會出現該錯誤。即時通訊使用實體框架代碼 - 首先,所有的模型都生成了,即時通訊試圖將多個表與相互聯繫在一起。 「顯示他們的項目數據和彈性工作制的所有用戶」(現在彈性工作制只是一個小數)」對象引用未設置爲對象的實例。「嵌套列表ASP.NET MVC LINQ實體框架

型號:

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

請幫忙。

+0

有關例外:看http://stackoverflow.com/q/4660142/121309一個提示:什麼是flexModel的'價值.Flex'在那條錯誤線上,爲什麼? – 2014-10-07 12:48:19

+0

幾乎你的對象是空的,你從你的控制器發送 – jbutler483 2014-10-07 12:48:34

+0

是的,這對我沒有多大幫助。爲什麼它是空的? – Qvadriologic 2014-10-07 12:49:55

回答

2

StaffModelFlex財產從不實例化,所以當你試圖在其訪問的方法,你得到的NullReferenceException。構造函數添加到您的類像這樣將其創建爲一個空對象:

public class StaffModel 
{ 
    public StaffModel() 
    { 
     Flex = new FlexModel(); 
    } 

    //snip 
} 
相關問題