学海无涯

导航

EF Core 关系配置 一对一

一个订单对应一个快递信息

在一对多关系中,EF Core 会自动在多端的表中生成一个指向一端的外键列,不需要我们显式地声明外键属性。但是在一对一关系中,必须显式地在其中一个实体类中声明一个外键属性。

 实体类:

/// <summary>
    /// 订单
    /// </summary>
    public class Order
    {
        public long Id { get; set; }
        /// <summary>
        /// 商品名称
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 收货地址
        /// </summary>
        public string Address { get; set; }
        /// <summary>
        /// 快递信息
        /// </summary>
        public Delivery? Delivery { get; set; } 
    }

  

 /// <summary>
    /// 快递信息
    /// </summary>
    public class Delivery
    {
        public long Id { get; set; }
        /// <summary>
        /// 快递公司名称
        /// </summary>
        public string CompanyName { get; set; }
        /// <summary>
        /// 快递单号
        /// </summary>
        public string Number { get; set; }
        /// <summary>
        /// 订单
        /// </summary>
        public Order Order { get; set; }
        /// <summary>
        /// 指向订单的外键
        /// </summary>
        public long OrderId { get; set; }
    }

  表结构:

 实体配置类:

 public class OrderConfig : IEntityTypeConfiguration<Order>
    {
        public void Configure(EntityTypeBuilder<Order> builder)
        {
            builder.ToTable("T_Orders");
            builder.Property(m => m.Address).IsUnicode();
            builder.Property(m => m.Name).IsUnicode();
            //声明一对一关系,并且外键OrderId在Delivery表中,一对一关系外键必须声明
            //此关系也可以声明在Delivery配置文件中,效率一样
            builder.HasOne<Delivery>(m => m.Delivery).WithOne(n => n.Order)
                .HasForeignKey<Delivery>(d => d.OrderId);
        }
    }

  

 public class DeliveryConfig : IEntityTypeConfiguration<Delivery>
    {
        public void Configure(EntityTypeBuilder<Delivery> builder)
        {
            builder.ToTable("T_Deliveries");
            builder.Property(d => d.CompanyName).IsUnicode(true).HasMaxLength(10);
            builder.Property(d => d.Number).HasMaxLength(50);
        }
    }

  插入数据:

 [HttpPost("Create")]
        public async Task<ActionResult> Create()
        {
            Order order = new Order();
            order.Address = "湖南省长沙市岳阳临湘大市场";
            order.Name = "USB 充电器";

            Delivery delivery = new Delivery();
            delivery.CompanyName = "蜗牛快递";
            delivery.Number = "SN356565565";
            delivery.Order = order;
            //EF Core 会自动保存 delivery.Order 属性,无须添加order到DBContext
            _context.Deliveries.Add(delivery);
            await _context.SaveChangesAsync();
            return Ok();
        }

  

posted on 2022-09-30 10:19  宁静致远.  阅读(119)  评论(0编辑  收藏  举报