【发布时间】:2020-01-22 06:19:03
【问题描述】:
我有 4 个表,其中 3 个用于一个项目的类别和子类别。
类别
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
public string Slug { get; set; }
public string Body { get; set; }
public ICollection<Item> Items { get; set; }
public ICollection<Product> Products { get; set; }
}
产品
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
//Product can have many items
public ICollection<Item> Items { get; set; }
//Product can have many brands
public ICollection<Brand> Brands { get; set; }
}
品牌
public class Brand
{
public int BrandId { get; set; }
public string BrandName { get; set; }
public int ProductId { get; set; }
public Product Product { get; set; }
//Brand can have many items.
public ICollection<Item> Items { get; set; }
}
Item.cs
public class Item
{
public int ItemId { get; set; }
[Required]
[StringLength(255, MinimumLength = 3)]
[Display(Name = "Item's Name")]
public string Name { get; set; }
public string ImagePath { get; set; }
[AllowHtml]
public string Description { get; set; }
[Required]
public decimal Price { get; set; }
public DateTime CreatedOn { get; set; }
public bool IsActived { get; set; }
public bool IsDeleted { get; set; }
public bool IsDiscounted { get; set; }
[Required]
[Display(Name = "Category")]
public int CategoryId { get; set; }
public Category Category { get; set; }
[Required]
[Display(Name = "Product")]
public int ProductId { get; set; }
public Product Product { get; set; }
[Required]
[Display(Name = "Brand")]
public int BrandId { get; set; }
public Brand Brand { get; set; }
}
项目表示例:
id name categoryId productId BrandId
---------------------------------------------------------
1 Google Phone 1 1 1
现在我想在项目视图中显示表品牌中的名称。我曾尝试使用 include,但它只能向视图显示一个相关表。
这是我的代码:
控制器
public ActionResult Browse(string name)
{
var genreModel = db.Products.Include("Items")
.SingleOrDefault(g => g.Name == name);
var viewModel = new BrowseViewModel
{
Product = genreModel
};
return View(viewModel);
}
查看模型:
public class BrowseViewModel
{
public Product Product { get; set; }
public Item Item { get; set; }
public Brand Brand { get; set; }
}
查看:
@model eStore.ViewModels.BrowseViewModel
@foreach (var item in Model.Product.Items)
<li><img src="/Images/Uploads/items/@item.ItemId/Thumbs/@item.ImagePath" class="img-responsive"></li>
<li>@Html.ActionLink(item.Name, "Detail", "Shop", new { id = item.ItemId }, null)</li>
<li>@item.Price</li>
<li>@item.Brand.BrandName</li>
当我运行项目并浏览项目名称时,我收到此错误:
System.NullReferenceException:对象引用未设置为对象的实例。
【问题讨论】:
-
您的示例代码不清楚。请给我们更多详细信息
BrowseViewModel、Product、Items班级。 -
嗨,很抱歉不清楚。我刚刚在我的帖子中添加了代码。
-
您好,欢迎来到stackoverflow,如果返回数据到视图,您是否检查了Model.Product.Items,通常此错误是由于模型为空
标签: asp.net asp.net-mvc linq