gpt4 book ai didi

entity-framework-core - EF Core 能否在需要两端的地方配置 "real"一对一关系?

转载 作者:行者123 更新时间:2023-12-04 02:15:34 24 4
gpt4 key购买 nike

EF Core documentation about One-To-One relations说:“当配置与 Fluent API 的关系时,您使用 HasOneWithOne 方法。” 仔细观察会发现这配置了 One -To-ZeroOrOne 或 ZeroOrOne-To-ZeroOrOne 关系取决于是否使用 IsRequired。示例:

public class ParentEntity
{
public Int64 Id { get; set; }
public ChildEntity Child { get; set; }
}

public class ChildEntity
{
public Int64 Id { get; set; }
public ParentEntity Parent { get; set; }
}

派生上下文类包含:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ParentEntity>().HasOne(p => p.Child).WithOne(d => d.Parent)
.HasForeignKey<ChildEntity>("ParentFk").IsRequired();
}

使用此配置,context.SaveChangescontext.Add(new ChildEntity()) 之后按预期失败(SqlException:无法将值 NULL 插入到列 'ParentFk' ... 因为 IsRequired) 但在 context.Add(new ParentEntity())context.Add(new ChildEntity() { Parent = new ParentEntity() }),即 ParentEntity-ChildEntity 关系是一对零或一。换句话说: child 的 parent 是必需的, parent 的 child 是可选的。

有没有办法在两端都需要的情况下配置“真正的”一对一关系?

也许这不能在数据库中强制执行。但它可以由 EF Core 强制执行吗? (顺便说一句:它可以由 EF6 强制执行。)

最佳答案

Is there a way to configure a "real" One-To-One relation where both ends are required?

在撰写本文时(EF Core 2.1.2),答案是否定的(不幸的是)。

Required and Optional Relationships文档部分说:

You can use the Fluent API to configure whether the relationship is required or optional. Ultimately this controls whether the foreign key property is required or optional.

还有一个关闭的issue EF Core 2: One to One Required Not Being Enforced (also Navigation no longer needed?) #9152问同样的问题,部分回复是:

when a relationship is made "Required" it means that a dependent entity cannot exist without an associated principal entity. This is done my making the FK non-nullable--i.e. the FK value must reference some principal entity.

However, it says nothing about the principal entity existing without the dependent. This is always possible because there isn't really any way to restrict it when working with partially loaded graphs. (This was the same with the old stack, although there were some situations where the state manager would, almost arbitrarily, stop certain things happening.) With stronger semantics applied to aggregates that limit partially loading of graphs it may be possible to enforce such a restriction in the future, but that isn't done yet.

关于entity-framework-core - EF Core 能否在需要两端的地方配置 "real"一对一关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52169036/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com