在使用Web API时,基于约定的实体框架核心(Entity Framework Core)返回与外键关联的对象,通常涉及到以下几个基础概念:
Orders
表可能有一个外键指向Customers
表的主键,表示每个订单属于哪个客户。Customer
实体可能有一个Orders
导航属性,表示该客户的所有订单。原因:
解决方法:
Include
方法显式加载关联的数据。例如:Include
方法显式加载关联的数据。例如:假设有两个实体Customer
和Order
,它们之间是一对多的关系:
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public List<Order> Orders { get; set; }
}
public class Order
{
public int Id { get; set; }
public int CustomerId { get; set; }
public Customer Customer { get; set; }
}
在DbContext
中配置这些实体:
public class ApplicationDbContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
public DbSet<Order> Orders { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>()
.HasOne(o => o.Customer)
.WithMany(c => c.Orders)
.HasForeignKey(o => o.CustomerId)
.OnDelete(DeleteBehavior.Cascade);
}
}
在控制器中查询并返回关联的数据:
[HttpGet("customers/{id}/orders")]
public async Task<IActionResult> GetCustomerOrders(int id)
{
var customer = await _context.Customers
.Include(c => c.Orders)
.FirstOrDefaultAsync(c => c.Id == id);
if (customer == null)
{
return NotFound();
}
return Ok(customer.Orders);
}
领取专属 10元无门槛券
手把手带您无忧上云