class Delivery
{
public int Id { get; set; }
public string CompanyName { get; set; }
public string Number { get; set; }
public Order Order { get; set; }
public int OrderId { get; set; }
}
class DeliveryConfig : IEntityTypeConfiguration<Delivery>
{
public void Configure(EntityTypeBuilder<Delivery> builder)
{
builder.ToTable("delivery");
}
}
class Order
{
public int Id { get; set; }
public string Name { get; set; }
public Delivery Delivery { get; set; }
}
class OrderConfig : IEntityTypeConfiguration<Order>
{
public void Configure(EntityTypeBuilder<Order> builder)
{
builder.ToTable("order");
// 设置一对一映射,需要HasForeignKey指定OrderId为外键
builder.HasOne<Delivery>(o => o.Delivery).WithOne(d => d.Order).HasForeignKey<Delivery>(d => d.OrderId);
}
}
private static Task GetOrder(MyDbContext ctx)
{
// 不使用include(),拿不到对应的order,但是可以拿到orderId。
Delivery d = ctx.Deliveries.FirstOrDefault();
// 使用include(),可以拿到对应的delivery。
//Order o = ctx.Orders.Include(o => o.Delivery).FirstOrDefault();
Console.WriteLine(d.CompanyName);
return Task.CompletedTask;
}
private static async Task SaveOrder(MyDbContext ctx)
{
Order o = new Order()
{
Name = "order1",
};
Delivery d = new Delivery()
{
CompanyName = "company01",
Order = o,
};
ctx.Deliveries.Add(d);
await ctx.SaveChangesAsync();
}