我試圖學習ASP.Net Core,而且我很難弄清楚如何在MVC'樣式'(?)中移動數據。我所關注的微軟網站上的ASP.NET Core教程並不涉及模型之間的任何關係。 (對他們來說,似乎是一個愚蠢的疏忽?)也許我的Google-Fu關閉了,所以如果這是明顯的,或者任何人有一些閱讀材料,我可以看看ASPNETCore,我會很感激。理解如何在ASP.net中處理數據時遇到問題核心
我有兩個模型。一個叫設備,另一個叫做設備類型。 在我的設備模型中,我有一個對DeviceType屬性的引用。
public class Device{
[Key]
public int ID {get; set;}
[Required]
[Display(Name = "Device Name")]
public String deviceName {get; set;}
[Required]
[Display(Name="Description")]
public String deviceDescription {get; set;}
[Required]
[Display(Name="Type")]
public DeviceType deviceType{get; set;}
}
public class DeviceType{
[Key]
public int ID {get; set;}
[Required]
[Display(Name="Type")]
public String name {get;set;}
[Required]
[Display(Name="Description")]
public String description {get;set;}
}
我想知道如何爲每個動作(CRUD)引用並獲取特定Device對象的deviceType。我也不明白如何在處理我的視圖時參考相關的設備類型。
GET創建 *如何讓我的DeviceTypes的選擇列表,以便用戶可以創建一個設備,然後選擇它是什麼類型的設備? *我對View部分做了一些研究,看起來我需要使用速記Razor「@ model.SelectList()」的語法,但這些參數讓我感到困惑。我不明白它要求什麼。以下是控制器現在的操作。
public IActionResult Create()
{
return View();
}
指數 *在顯示所有設備的循環,我將如何還包括在設備的結果表中的設備類型的名字嗎? *在視圖中,我會假設我可以使用@ Html.LabelFor來顯示數據的名稱是什麼,但是如何獲得實際值?
public async Task<IActionResult> Index()
{
return View(await _context.Device.ToListAsync());
}
更新/編輯 *我怎麼會檢索設備對象設備類型,然後允許用戶編輯呢?
// GET: Devices/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var device = await _context.Device.SingleOrDefaultAsync(m => m.ID == id);
if (device == null)
{
return NotFound();
}
return View(device);
}
刪除 *我還沒有在這看着呢,但我在這裏把它在編程的情況下其他動作時,那裏有什麼注意事項?
// GET: Devices/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var device = await _context.Device
.SingleOrDefaultAsync(m => m.ID == id);
if (device == null)
{
return NotFound();
}
return View(device);
}
同樣,如果除了微軟的「用Mac和Linux構建一個帶有Visual Studio代碼的asp.net核心應用程序」外,我還可以看到其他一些資源,這將解釋如何在視圖/控制器內部的模型中引用關係,這很好。
謝謝
EF Core尚未對延遲加載進行加載。 https://docs.microsoft.com/en-us/ef/core/querying/related-data – Alexan
@Alex:是的,我忘了這一點。或者,也許我只是覺得他們已經排序了將近兩年;)。沒什麼大不了。老實說,我還沒有看到很多好的理由來延遲加載,反正。一般來說,你只需要加載你需要的一切。 –
即使EF支持它,也不要在網絡應用程序中使用延遲加載,只要您可以提供幫助。這是爲什麼:http://ardalis.com/avoid-lazy-loading-entities-in-asp-net-applications – ssmith