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 实例中的关系时,我得到了一些错误.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.
是否需要 Class1 还具有 Class2 类型的属性才能使 EF Core 正常工作?
Does Class1 is required to have also a property of type Class2 in order for EF Core to work correctly?
推荐答案
是否需要 Class1 还具有 Class2 类型的属性才能使 EF Core 正常工作?
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
属性作为 PK 和 FK 到 Class2
,在这种情况下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屋!