2

How to write a one-to-one--or-zero relationship using fluent api? Can someone help me out correct what i have written. I am not sure if its correct.

The scenario : One Student Can have one or zero Address.

Student Model

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

Address Model

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

    public Student Student { get; set; }

What I tried:

        builder.HasOne(u => u.Address)
        .WithOne(b => b.Student)
        .HasForeignKey<Address>(b => b.StudentId);
Illep
  • 16,375
  • 46
  • 171
  • 302

2 Answers2

5

In case of one-to-one--or-zero relationship you don't need additional PrimaryKey along with the ForeignKey in dependent table. Primarykey of the Principle table will also be the PrimaryKey and ForeignKey of the dependent table at the same time.

So write your Address model class as follows:

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

Then in the Fluent API configuration:

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);
    }
}
TanvirArjel
  • 30,049
  • 14
  • 78
  • 114
0

To configure a one-to-zero-or-one relationship between the Student and Address entities with fluent api you can use HasOptional(s => s.Address) method like

modelBuilder.Entity<Student>()
            .HasOptional(s => s.Address) // Address property is optional in Student entity
            .WithRequired(ad => ad.Student); // Student property is required 
Llazar
  • 3,167
  • 3
  • 17
  • 24