Karthic G
Karthic G

Reputation: 1182

What is the best method for Required-to-Optional Relationship (One-to–Zero-or-One) in EF Core?

I have implemented the project of EntityFramework 6 into EntityFramework Core. I have to do migrate EF6 relationship pattern into EF core . I found some references below:

  1. Entity Framework Core zero-or-one to zero-or-one relation

but didn't get any ideas on required-optional relationship in EF-Core.

Sample1.cs:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<StudentAddress>()
                .HasRequired(x => x.Student)
                .WithOptional(x => x.StudentAddress);
}

public class Student
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }
    public virtual StudentAddress StudentAddress { get; set; }
}

public class StudentAddress
{
    public int StudentId { get; set; }
    public string State { get; set; }
    public virtual Student Student { get; set; }
}

Sample2.cs:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<StudentAddress>()
                .HasKey(sa => sa.StudentId);
    modelBuilder.Entity<StudentAddress>()
                .HasRequired(x => x.Student)
                .WithOptional(x => x.StudentAddress);
}

public class Student
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }
    public virtual StudentAddress StudentAddress { get; set; }
}

public class StudentAddress
{
    public int StudentId { get; set; }
    public string State { get; set; }
    public virtual Student Student { get; set; }
}

Kindly someone help me that how to do that in EF-Core using fluent api

Upvotes: 1

Views: 1709

Answers (1)

dglozano
dglozano

Reputation: 6607

You can try this (Ref.: docs):

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<StudentAddress>()
                .HasOne(x => x.Student)
                .WithOne(x => x.StudentAddress).IsRequired(false);
}

Alternatively, you could add a FK StudentAddressId in your Student Model an have the type be nullable int?

public class Student
{
    public int StudentId { get; set; }
    
    // This is the FK for StudentAddress.
    // Make it int? (nullable) if StudentAddress is optional
    public int? StudentAddressId { get; set; }
    public virtual StudentAddress StudentAddress { get; set; }
}

public class StudentAddress
{
    public int StudentId { get; set; }

    public virtual Student Student { get; set; }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // Since the FK is nullable, you don't need the IsRequired(false)
    modelBuilder.Entity<StudentAddress>()
                .HasOne(x => x.Student)
                .WithOne(x => x.StudentAddress);
}

Upvotes: 2

Related Questions