我正在尋找基於另一個表從我的表中選擇一個列表。我需要檢索屬於特定系統系列的系統名稱。我已經添加了外鍵。我創建了一個包含這兩個類的ViewModel,但它引發了空指針異常。我是MVC的新手,我不確定自己錯在哪裏。MVC5:外鍵和數據訪問
模型類:系統 公共類系統 {
public int SystemsID { get; set; }
public string SystemName { get; set; }
public DateTime CreatedOn { get; set;}
public string CreatedBy { get; set; }
public int SystemFamilyID { get; set; }
public virtual SystemFamily SystemFamily { get; set; }
}
類SystemFamily
public class SystemFamily
{
public int SystemFamilyID { get; set;}
public int SystemsID {get;set;}
public string FamilyName { get; set; }
public DateTime DateCreated { get; set; }
public string CreatedBy { get; set; }
public virtual ICollection<Systems> Systems { get; set; }
}
ViewSystem是我SystemFamilyController的方法。
public ActionResult ViewSystem(int? id)
{
var viewmodel = new Sys_SysFam();
ViewBag.SystemFamilyID = id.Value;
//if (id != null)
//{
// ViewBag.SystemFamilyID = id.Value;
// viewmodel.Systems = viewmodel.SystemFamily.Where(
// i => i.SystemFamilyID == id.Value).Single().Systems;
//}
return View(viewmodel);
}
的觀點:
@model SystemFam_System.ViewModel.Sys_SysFam
@{
ViewBag.Title = "ViewSystem";
}
<h2>ViewSystem</h2>
<p>@ViewBag.SystemFamilyID</p>
<table>
@foreach (var item in Model.Systems)
{
string selectedRow = "";
if (item.SystemFamilyID == ViewBag.SystemFamilyID)
{
//{
// selectedRow = "success";
//}
<tr class="@selectedRow">
<td>
@item.SystemName
</td>
<td>
@item.SystemsID
</td>
<td>
@item.SystemFamily
</td>
</tr>
}
}
</table>
我得到空指針異常。我想查看屬於視圖系統中特定家庭的系統。
在此先感謝! VINI
編輯:
public class Sys_SysFam
{
public IEnumerable<Systems> Systems { get; set; }
public SystemFamily SystemFamily { get; set; }
}
感謝您的回答。但我無法解決_DataContext_ – Vini
您是否使用實體框架orm進行數據庫操作或Ado.Net? –
DataContext我用來查詢數據庫獲取數據 –