仅在EF Core中为"true"创建唯一约束

Val*_*tor 3 c# sql-server entity-framework-core

我有一个跟踪记录附件的课程.每个记录可以有多个RecordAttachments,但是要求每个记录只能有一个RecordAttachment标记为IsPrimary.

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; }
}
Run Code Online (Sandbox Code Playgroud)

我不能只使用.HasIndex(e => new { e.RecordId, e.IsPrimary }).IsUnique(true)因为false每个记录可以有多个值.

基本上,我需要一个唯一约束RecordIdIsPrimary == true,虽然这并不工作:

entity.HasIndex(e => new { e.RecordId, IsPrimary = (e.IsPrimary == true) }).IsUnique(true)

编辑:查看这样的答案:比特列的唯一约束只允许1个真(1)值看起来这可能直接用SQL创建约束,但是它不会反映在我的模型中.

Iva*_*oev 11

您可以使用HasFilterfluent API 指定索引过滤器.

不幸的是,它不是数据库不可知的,因此您必须使用目标数据库SQL语法和实际的表列名称.

对于Sql Server,它将是这样的:

.HasIndex(e => new { e.RecordId, e.IsPrimary })
.IsUnique()
.HasFilter("[IsPrimary] = 1");
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅关系数据库建模 - 索引文档主题.

  • @Valuator为此,您可以使用`nameof`。 (2认同)
  • 使用 nameof 的示例: .HasIndex(e => new { e.RecordId, e.IsPrimary }).IsUnique().HasFilter($"[{nameof(RecordAttachment.IsPrimary)}] = 1"); (2认同)