.NET Core 6 MVC Code First:如何将3表数据合并为指定JSON列表
解决方案
首先定义一个DTO(数据传输对象),完全匹配你期望的JSON结构:
public class ProductDto { public Guid Id { get; set; } public string Name { get; set; } public int Quantity { get; set; } public string Category { get; set; } }
假设你的数据库有Products、Inventories、Categories三张表,关联逻辑为Product对应一条Inventory记录,且归属一个Category。通过EF Core的Linq查询关联数据并映射到DTO即可:
示例查询实现
using Microsoft.EntityFrameworkCore; // 替换为你的DbContext类名 public async Task<List<ProductDto>> GetFormattedProducts() { // 方式1:使用Join关联查询 var products = await _context.Products .Join(_context.Inventories, product => product.Id, inventory => inventory.ProductId, (product, inventory) => new { product, inventory }) .Join(_context.Categories, pi => pi.product.CategoryId, category => category.Id, (pi, category) => new ProductDto { Id = pi.product.Id, Name = pi.product.Name, Quantity = pi.inventory.Quantity, Category = category.Name }) .ToListAsync(); return products; }
更简洁的Eager Loading写法
如果实体类已配置好导航属性,可直接用Include加载关联数据再映射:
var products = await _context.Products .Include(p => p.Inventory) .Include(p => p.Category) .Select(p => new ProductDto { Id = p.Id, Name = p.Name, Quantity = p.Inventory.Quantity, Category = p.Category.Name }) .ToListAsync();
在MVC Controller返回JSON
将查询结果直接返回,ASP.NET Core会自动序列化为你需要的JSON格式:
public async Task<IActionResult> GetProducts() { var formattedProducts = await GetFormattedProducts(); return Json(formattedProducts); }
注意事项
- 确保实体类的关联关系(外键、导航属性)配置正确,否则查询会失败。
- 若你的表结构、关联逻辑和示例不同,只需调整关联字段和映射逻辑即可。
内容的提问来源于stack exchange,提问作者Nguen
相关产品推荐
相关产品推荐

