EF Core one-to-zero relationship one way

£可爱£侵袭症+ 提交于 2021-02-16 06:11:02

问题


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:


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)


来源:https://stackoverflow.com/questions/49070328/ef-core-one-to-zero-relationship-one-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!