在ASP.NET Core中使用Entity Framework Core时,可以通过以下步骤访问关联关系:
Order
类和一个Customer
类,可以使用以下代码定义它们之间的一对多关系:public class Order
{
public int Id { get; set; }
public string OrderNumber { get; set; }
public int CustomerId { get; set; }
public Customer Customer { get; set; }
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public List Orders { get; set; }
}
DbContext
来查询和保存数据。在你的POST方法中,你可以接收一个包含表单数据的视图模型,并使用关联关系来设置相关实体的属性。public class OrderViewModel
{
public string OrderNumber { get; set; }
public int CustomerId { get; set; }
}
public class OrdersController : Controller
{
private readonly ApplicationDbContext _context;
public OrdersController(ApplicationDbContext context)
{
_context = context;
}
[HttpPost]
public IActionResult Create(OrderViewModel model)
{
if (ModelState.IsValid)
{
var order = new Order
{
OrderNumber = model.OrderNumber,
CustomerId = model.CustomerId
};
_context.Orders.Add(order);
_context.SaveChanges();
return RedirectToAction("Index");
}
// 如果模型验证失败,返回视图以显示错误消息
return View(model);
}
}
以上代码示例演示了如何在提交类型表单时访问关联关系。在控制器的POST方法中,你可以使用表单数据创建新的实体对象,并将关联实体的ID设置为所选值。然后,通过保存更改来将新实体插入到数据库中。