我的数据库中有产品,库存和库存表库存表包含产品(ProductId)和存储(StorageID)的外键。现在,我试图以模式显示产品详细信息。我现在可以在模式中显示的信息是ProductName,Price和StorageId。我不愿意显示StorageId,但是我想显示该产品可用的位置(StorageName)。所以我需要在我的视图中包括存储表...
问题是我无法在控制器中包括存储表,而不能仅包括库存表。有什么解决办法吗?这是我的控制器...
public async Task<IActionResult> Details(long? id)
{
var products = await _context.Products.Include(s => s.Stock)
.FirstOrDefaultAsync(s => s.ProductId == id);
return View(products);
}
这是我的ProductModel
public partial class Products
{
public Products()
{
Stock = new HashSet<Stock>();
}
public long ProductId { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public ICollection<Stock> Stock { get; set; }
}
}
和StockModel
public partial class Stock
{
public long StockId { get; set; }
public long Quantity { get; set; }
public long? ProductId { get; set; }
public int? StorageId { get; set; }
public Products Product { get; set; }
public Storage Storage { get; set; }
}
}
您可以像这样使用EF Core的ThenInclude()
扩展方法:
public async Task<IActionResult> Details(long? id)
{
var products = await _context.Products
.Include(p => p.Stock)
.ThenInclude(s => s.Storage)
.FirstOrDefaultAsync(p => p.ProductId == id);
return View(products);
}