我正在处理支付设备.设备所有者必须获得终端ID(TID),该终端ID是批量获取的,然后与特定设备相关联.因此,设备可能有也可能没有TID(但如果有,则只能有一个TID),并且TID可能与设备关联,也可能不与设备关联(但如果有,则只能与一个设备关联).
Device
和Tid
两个型号都已经存在,我想添加它们之间的联系.
我添加了如下导航属性(为清楚起见,删除了所有其他属性)...
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,如果这有什么不同的话.