我有一个用于跟踪记录附件的类。每个 Record 可以有多个 RecordAttachment,但要求每个 Record 只能有一个标记为 IsPrimary
的 RecordAttachment。
public class RecordAttachment
{
public int Id { get; set; }
public int RecordId { get; set; }
public string Details { get; set; }
public bool IsPrimary { get; set; }
public Record Record { get; set; }
}
我不能只使用 .HasIndex(e => new { e.RecordId, e.IsPrimary }).IsUnique(true)
因为可以有多个 false
每个记录的值。
基本上我需要对 RecordId
和 IsPrimary == true
进行唯一约束,尽管这不起作用:
entity.HasIndex(e => new { e.RecordId, IsPrimary = (e.IsPrimary == true) }).IsUnique(true)
编辑: 查看这样的答案:Unique Constraint for Bit Column Allowing Only 1 True (1) Value这似乎可以直接使用 SQL 创建约束,但它不会反射(reflect)在我的模型中。
最佳答案
您可以使用 HasFilter
指定索引过滤器流畅的 API。
不幸的是,它与数据库无关,因此您必须使用目标数据库 SQL 语法和实际的表列名称。
对于 Sql Server,它将是这样的:
.HasIndex(e => new { e.RecordId, e.IsPrimary })
.IsUnique()
.HasFilter("[IsPrimary] = 1");
或
.HasIndex(e => new { e.RecordId, e.IsPrimary })
.IsUnique()
.HasFilter($"[{nameof(RecordAttachment.IsPrimary)}] = 1");
有关详细信息,请参阅 Relational Database Modeling - Indexes文档主题。
关于c# - 仅在 EF Core 中为 'true' 创建唯一约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50069427/