【问题标题】:Writing One to one relationship using Fluent API使用 Fluent API 编写一对一关系
【发布时间】:2018-12-26 17:41:30
【问题描述】:

如何使用fluent api编写one-to-one--or-zero关系?有人可以帮我纠正我写的东西。我不确定它是否正确。

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

学生模型

    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);

【问题讨论】:

  • 这是 EF 核心 2.1。
  • 地址模型中的 StudentId 应声明为 int。
  • @vinicius.ras 是的。已更正。
  • 顺便说一句,您的解决方案非常好。接受答案的解决方案也很好,但不是强制性的

标签: c# entity-framework-core ef-fluent-api


【解决方案1】:

one-to-one--or-zero 关系的情况下,您不需要额外的PrimaryKey 以及依赖表中的ForeignKeyPrinciple 表的Primarykey 也将同时是依赖表的PrimaryKeyForeignKey

所以写你的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);
    }
}

【讨论】:

  • OP 不是“接近解决方案”。 EF Core 支持一对一的共享 PK(您的)和 FK(OP)。
  • 谢谢!但是共享PK让它更明智!
【解决方案2】:

要使用 fluent api 在 Student 和 Address 实体之间配置 one-to-zero-or-one 关系,您可以使用 HasOptional(s =&gt; s.Address) 方法,例如

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

【讨论】:

  • 这是为 EF 而不是 EF Core!
猜你喜欢
  • 2019-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-03
相关资源
最近更新 更多