EF Core one-to-zero relationship one way

c# entity-framework-core

Question

Can a relationship one-to-one be created only one way?

public class Class1
{
   [Key]
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public int Class1Id { get; set; }
   ...
}

public class Class2
{
   [Key]
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public int Class2Id { get; set; }

   public int? RelationshipId { get; set; }

   public virtual Class1 Relationship { get; set; }

   ...
}

And the configuration looks like this

public void Configure(EntityTypeBuilder<Class2> builder)
{
   builder.ToTable("...");

   builder.HasOne(m => m.Relationship)
     .WithOne()
     .HasForeignKey<Class1>(a => a.Class1Id);
}

But when I try to inspect the Relationship in an instance of Class2 I get something wrong. The RelationshipId has a value and the Relationship.Class1Id has a different value. The Relationship.Class1Id has the same value as Class2Id.

Does Class1 is required to have also a property of type Class2 in order for EF Core to work correctly?

1
6
2/25/2020 8:24:35 AM

Accepted Answer

Does Class1 is required to have also a property of type Class2 in order for EF Core to work correctly?

No. The mistake is in FK mapping:

.HasForeignKey<Class1>(a => a.Class1Id)

This way you are telling EF that it should use Class1Id property of the Class1 as both PK and FK to Class2, in which case the RelationshipId property of Class2 is not treated as a FK, but like any other simple property.

Instead, you should specify the FK property of the relationship (1) is on Class2 and (2) is called RelationshipId:

builder.HasOne(e => e.Relationship)
    .WithOne()
    .HasForeignKey<Class2>(e => e.RelationshipId);
//                   ^                 ^
//                  (1)               (2)
14
10/2/2019 12:14:11 AM


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