Writing One to one relationship using Fluent API

c# ef-fluent-api entity-framework-core

Question

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);
1
1
12/26/2018 5:46:18 PM

Accepted Answer

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);
    }
}
4
12/26/2018 6:31:03 PM

Popular Answer

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 


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow