所以,我是編程新手,我正在嘗試制作我的第一個 .net 專案,但我被卡住了。
我有一個包含表產品的資料庫,它看起來像這樣:
[Key]
public int ProductId { get; set; }
public string ProductName { get; set; }
[Range(1, int.MaxValue)]
public double ProductPrice { get; set; }
public string ProductDescription { get; set; }
public string ProductImagePath { get; set; }
public int ProductColorId { get; set; }
[ForeignKey("ProductColorId")]
public virtual ProductColor ProductColor { get; set; }
public int ProductShippingOptionId { get; set; }
[ForeignKey("ProductShippingOptionId")]
public virtual ProductShippingOption ProductShippingOption { get; set; }
public int ProductConditionId { get; set; }
[ForeignKey("ProductConditionId")]
public virtual ProductCondition ProductCondition { get; set; }
ProductShippingOption、ProductColor 和 ProductCondition 列是單獨的表,每個表都包含 Id 和 Name 列。
當我將產品添加到資料庫時,我想在視圖中僅顯示一個產品的詳細資訊,但我需要顯示 ProductConditionName 而不是 ProductConditionId(例如)。
我應該在我的 ViewModel 和我的控制器中包含什么以便我可以在我的視圖中使用它?
我在 ProductController 中的操作如下所示
public IActionResult ProductTemplate(int? id)
{
ProductVM productVM = new ProductVM()
{
Product = _db.Product.Find(id),
};
if (id == 0)
{
return NotFound();
}
if (id == 0)
{
return NotFound();
}
if(productVM==null)
{
return NotFound();
}
return View(productVM);
}
謝謝!
uj5u.com熱心網友回復:
最好和最簡單的方法是在 Product 中包含類:
對于您的 ProductTemplate 操作:
ProductVM productVM = new ProductVM()
{
Product = _db.Product.Where(s=>s.Id == id)
.Include(s=>s.ProductColor)
.Include(s=>s.ProductShippingOption)
.Include(s=>s.ProductCondition)
.FirstOrDefault();
};
你可以在你的 .cshtml 中呼叫它們(假設你想要 ProductColor 名稱):
@Model.ProductColor.Name
或者,您可以添加Include()到您的背景關系以默認獲取所有包含。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/446707.html
標籤:C# 网 asp.net-mvc 实体框架
下一篇:GridView僅填充1個結果
