我正在处理支付设备.设备所有者必须获得终端ID(TID),该终端ID是批量获取的,然后与特定设备相关联.因此,设备可能有也可能没有TID(但如果有,则只能有一个TID),并且TID可能与设备关联,也可能不与设备关联(但如果有,则只能与一个设备关联).

DeviceTid两个型号都已经存在,我想添加它们之间的联系.

我添加了如下导航属性(为清楚起见,删除了所有其他属性)...

public class Device {
  public string? TidId { get; set; }
  public virtual Tid? Tid { get; set; }
}

public class Tid {
  public string? DeviceId { get; set; }
  public virtual Device? Device { get; set; }
}

当我try 为此添加迁移时,我收到错误"The dependent side could not be determined for the one-to-one relationship between 'Tid.Device' and 'Device.Tid'. To identify the dependent side of the relationship, configure the foreign key property. If these navigations should not be part of the same relationship, configure them independently via separate method chains in 'OnModelCreating'. See 100 for more details."

我try 遵循the Microsoft docs中的建议,这意味着将以下内容添加到数据库上下文中……

    builder.Entity<Device>()
      .HasOne<Tid>()
      .WithOne(t => t.Device)
      .HasForeignKey<Tid>()
      .IsRequired(false);

这添加了迁移,但当我try 更新数据库时,我收到错误"The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Tids_Devices_Id". The conflict occurred in database "abc", table "dbo.Devices", column 'Id'."

我的猜测(也许是错误的)是,因为我只在一个方向上指定了关系,所以关系中只有一方可以为空,而我需要两边都可以为空.

所以,我加上了另一边.

    builder.Entity<Tid>()
      .HasOne<Device>()
      .WithOne(d => d.Tid)
      .HasForeignKey<Device>()
      .IsRequired(false);

然而,我甚至不能为此添加迁移,因为它给了我错误"A relationship cycle involving the primary keys of the following entity types was detected: 'Device -> Tid'. This would prevent any entity to be inserted without violating the store constraints. Review the foreign keys defined on the primary keys and either remove or use other properties for at least one of them."

有谁能解释一下我是怎么安排的吗?我正在ASP.NET Blazor服务器应用程序中使用EF Core 7.0.0,如果这有什么不同的话.

推荐答案

你就快到了.您需要添加的是外键的显式语句...

    builder.Entity<Device>()
      .HasOne<Tid>()
      .WithOne(t => t.Device)
      .HasForeignKey<Tid>(t => t.DeviceId)
      .IsRequired(false);

    builder.Entity<Tid>()
      .HasOne<Device>()
      .WithOne(d => d.Tid)
      .HasForeignKey<Device>(d => d.TidId)
      .IsRequired(false);

我认为你应该会发现这是可行的.

Csharp相关问答推荐

后台线程上的延迟WriteableBitmap写入导致闪烁

PostingAsJsonAschange在从调用的方法返回时给出500错误

当Visual Studio处于升级管理模式时,无法安装Torch运行时

如何使用Unity和MRTK3将手网添加到Hololens 2应用程序中

System. InvalidOperationException:无法将数据库中的字符串值i转换为映射的ItemType枚举中的任何值''''

为什么这个Reflection. Emit代码会导致一个DDL ViolationException?

限制特定REST API不被访问,但部署代码

使页面内容居中

Amazon SP-API确认发货不设置&Quot;递送服务

SortedSet.Remove()不会删除SortedSet.Min返回的元素

在.NET 8最低API中从表单绑定中排除属性

MSTest--将消息直接写入StdOut和使用TestContext有什么不同?

HttpClient SendAsync与多线程环境中的ArchiveZip

如何在onNext之前等待订阅者完成?

Azure函数-在外部启动类中生成配置时出错

为什么Azure函数(独立工作进程)索引失败?使用Azure App配置的CosmosDbTrigger绑定失败,未解析为值

实体框架-IsRequired()与OnDelete()

两个DateTimeOffset之间的差异返回意外的负值

使用可空引用类型时C#接口实现错误

除非首先访问使用的终结点,否则本地API上的终结点不起作用