c# - 在 Entity Framework Core MVC 应用程序的视图中访问连接表中的数据
问题描述
我正在使用 Entity Framework Core 构建一个 MVC 应用程序,并且无法从我的视图中访问我想要的内容。我有 3 个表:产品、产品图像、图像。ProductImage 有一个 ProductId 和一个 ImageId 作为 Product 和 Image 表之间的链接。我在下面添加了我的模型(以简化形式)。
我的问题是我的cshtml(带有产品模型)中的以下内容会导致错误,因为图像为空。谁能告诉我这是我的模型、我的控制器还是其他什么问题?谢谢。
来自 .cshtml:
@foreach (var item in Model)
{
@item.ProductImages.FirstOrDefault().Image.FileId.ToString();
}
从我的控制器:
// GET: Products
public async Task<IActionResult> Index()
{
return View(await _context.Products
.Include(pi => pi.ProductImages)
.AsNoTracking().ToListAsync());
}
我的模型;
public class Product
{
public int Id { get; set; } // ID (Primary key)
public string Name { get; set; } // Name
// Reverse navigation
public virtual ICollection<ProductImage> ProductImages { get; set; }
public virtual Brand Brand { get; set; } // FK_Product_Brand_BrandId
public Product()
{
ProductImages = new List<ProductImage>();
}
}
public class ProductImage
{
public int ProductImageId { get; set; } // ProductImageID (Primary key)
public int ImageId { get; set; } // ImageID
public int ProductId { get; set; } // ProductID
public virtual Image Image { get; set; } // FK_ProductImage_Image_ImageId
public virtual Product Product { get; set; } // FK_ProductImage_Product_ProductId
}
public class Image
{
public int ImageId { get; set; } // ImageID (Primary key)
public string Caption { get; set; } // Caption
public virtual ICollection<ProductImage> ProductImages { get; set; } // ProductImage.FK_ProductImage_Image_ImageId
public Image()
{
ProductImages = new List<ProductImage>();
}
}
解决方案
预期的行为。FirstOrDefault
可能返回 null。
重写您的查询:
// GET: Products
public async Task<IActionResult> Index()
{
return View(await _context.Products
.Include(pi => pi.ProductImages.Take(1))
.ThenInclude(pi => pi.Image)
.AsNoTracking()
.ToListAsync());
}
在 .cshtml 中
@foreach (var item in Model)
{
@item.ProductImages.FirstOrDefault()?.Image.FileId.ToString() ?? "";
}
推荐阅读
- java - Java:为什么 else 语句总是在我的 while 循环中运行?
- python - Python Pandas 复合聚合不等于单个资产复合的总和
- python - 如何计算 Sklearn 中点到质心的平均距离的平均值?
- r - 如何使用列名向量作为 dplyr::group_by() 的输入?
- azure - 如何将用户分配的托管标识添加到 Azure 实验室 VM?
- unreal-engine4 - 错误:无法实例化模块“启动”:System.FormatException:输入字符串的格式不正确
- graphql - Shopify GraphQL Checkout 创建突变
- reactjs - react-datetime timeConstraints for timePicker 似乎不起作用
- python-3.x - 图像轮廓区域迭代计算器
- python - 如果 requirements.txt 未更改,则触发 docker 构建的最佳实践