代码之家  ›  专栏  ›  技术社区  ›  Illep

使用fluentapi编写一对一关系

  •  1
  • Illep  · 技术社区  · 7 年前

    如何写一篇文章 one-to-one--or-zero 使用fluentapi的关系?有人能帮我纠正一下我写的东西吗。我不确定它是否正确。

    场景:一个学生可以有一个或零个地址。

    学生模型

        public int Id{ get; set; }
        public string Name{ get; set; }
        public Address Address{ get; set; }
    

    地址模型

        public int Id { get; set; }
        public string Street{ get; set; }
        public int StudentId { get; set; }
    
        public Student Student { get; set; }
    

            builder.HasOne(u => u.Address)
            .WithOne(b => b.Student)
            .HasForeignKey<Address>(b => b.StudentId);
    
    2 回复  |  直到 7 年前
        1
  •  4
  •   TanvirArjel    7 年前

    万一 one-to-one--or-zero 你不需要额外的关系 PrimaryKey 随着 ForeignKey Primarykey Principle 表也将是 主关键字 外侨 同时创建依赖表的。

    所以写下你的 Address

    public class Address
    {
       public int StudentId { get; set; } // Here StudentId is the PrimaryKey and ForeignKey at the same time.
       public string Street{ get; set; }
    
       public Student Student { get; set; }
    }
    

    然后在 Fluent API 配置:

    public class AddressConfiguration : IEntityTypeConfiguration<Address>
    {
        public void Configure(EntityTypeBuilder<Address> builder)
        {
            builder.HasKey(u => u.StudentId)
            builder.HasOne(u => u.Student)
                   .WithOne(b => b.Address)
                   .HasForeignKey<Address>(b => b.StudentId);
        }
    }
    
        2
  •  0
  •   Llazar    7 年前

    one-to-zero-or-one HasOptional(s => s.Address)

    modelBuilder.Entity<Student>()
                .HasOptional(s => s.Address) // Address property is optional in Student entity
                .WithRequired(ad => ad.Student); // Student property is required