仅在 EF Core 中为“true"创建唯一约束 [英] Create Unique constraint for 'true' only in EF Core

查看:33
本文介绍了仅在 EF Core 中为“true"创建唯一约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于跟踪记录附件的类.每个 Record 可以有多个 RecordAttachment,但要求每个 Record 只能有一个 RecordAttachment 标记为 IsPrimary.

I have a class for tracking attachments to a Record. Each Record can have multiple RecordAttachments, but there is a requirement that there can only be one RecordAttachment per-Record that is marked as 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; }
}

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

I can't just use .HasIndex(e => new { e.RecordId, e.IsPrimary }).IsUnique(true) because there can be multiple false values per Record.

基本上我需要对 RecordIdIsPrimary == true 的唯一约束,尽管这不起作用:

Basically I need a unique constraint on RecordId and IsPrimary == true, although this didn't work:

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

查看这样的答案:位的唯一约束Column Allowing Only 1 True (1) Value 看来这可以直接用 SQL 创建约束,但它不会反映在我的模型中.

Looking at answers like this: Unique Constraint for Bit Column Allowing Only 1 True (1) Value it appears this would be possible creating the constraint directly with SQL, but then it wouldn't be reflected in my Model.

推荐答案

您可以使用 HasFilter 流畅的 API.

You can specify index filter using the HasFilter fluent API.

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

Unfortunately it's not database agnostic, so you have to use the target database SQL syntax and actual table column names.

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

For Sql Server it would be something like this:

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

    .HasIndex(e => new { e.RecordId, e.IsPrimary })
    .IsUnique()
    .HasFilter($"[{nameof(RecordAttachment.IsPrimary)}] = 1");

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

For more information, see Relational Database Modeling - Indexes documentation topic.

这篇关于仅在 EF Core 中为“true"创建唯一约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆