首页 > 解决方案 > 在 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>();
    }
}

这是视图中返回的内容: 在此处输入图像描述

标签: c#asp.net-mvcentity-frameworkasp.net-coreentity-framework-core

解决方案


预期的行为。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() ?? "";
}

推荐阅读