我在一个表中有两列,Rates
:
ZonePointAId
ZonePointBId
在引用ZoneId
表中单个Zones
列的两列上都带有外键。我想强制执行约束,无论找到值的顺序如何。 (无论首先列出哪个区域,区域之间的比率都相同)例如:
ZonePointAId = 63, ZonePointBId = 64 - Pass!
ZonePointAId = 63, ZonePointBId = 63 - Pass!
ZonePointAId = 64, ZonePointBId = 63 - Fail!
我已经尝试过此Unique Key constraints for multiple columns in Entity Framework中此处列出的解决方案,但是它们都允许插入反函数。我正在使用Postgres(如果重要,请使用RDS)。 .NET Core 3.1。
我试图避免为每个反向源/目标组合重复数据。任何见识将不胜感激。我什至不确定数据库是否能够做到这一点,更不用说通过注解或Fluent进行定义的EF Core了,但是我想知道是否有人知道这将是你们!
答案 0 :(得分:1)
至少在数据库级别,您可以基于表达式创建唯一索引。在这种情况下,请使用最小和最大函数对值进行“排序”:
create unique index AidBid_sameas_BidAid
on rates (least(ZonePointAId,ZonePointBId), greatest(ZonePointAId,ZonePointBId));