EF Core一对零关系的一种方式 [英] EF Core one-to-zero relationship one way
问题描述
可以仅以一种方式创建一对一关系吗?
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; }
...
}
配置看起来像这样
public void Configure(EntityTypeBuilder<Class2> builder)
{
builder.ToTable("...");
builder.HasOne(m => m.Relationship)
.WithOne()
.HasForeignKey<Class1>(a => a.Class1Id);
}
但是当我尝试检查Class2实例中的Relationship时,我得到了一些错误.RelationshipId具有一个值,而Relationship.Class1Id具有不同的值.Relationship.Class1Id与Class2Id具有相同的值.
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.
为了让EF Core正常工作,是否需要Class1也具有Class2类型的属性?
Does Class1 is required to have also a property of type Class2 in order for EF Core to work correctly?
推荐答案
为了让EF Core正常工作,是否需要Class1也具有Class2类型的属性?
Does Class1 is required to have also a property of type Class2 in order for EF Core to work correctly?
不.错误在于FK映射:
No. The mistake is in FK mapping:
.HasForeignKey<Class1>(a => a.Class1Id)
这样,您告诉EF它应同时使用 Class1
的 Class1Id
属性作为 Class2
的PK和FK Class2
的 RelationshipId
属性没有被视为FK,而是像其他任何简单属性一样.
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.
相反,您应该指定关系的FK属性(1)在 Class2
上,而(2)称为 RelationshipId
:
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)
这篇关于EF Core一对零关系的一种方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!