仅在EF Core中为“ true”创建唯一约束 [英] Create Unique constraint for 'true' only in EF Core
问题描述
我有一个用于跟踪记录附件的类。每个记录可以具有多个RecordAttachment,但是有一个要求,每个记录只能有一个标记为 IsPrimary
的RecordAttachment。
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.
基本上,我需要对 RecordId
和 IsPrimary == true $的唯一约束c $ c>,尽管这不起作用:
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)
编辑:
看着这样的答案:位列的唯一约束,仅允许1个真(1)值,看来可以直接用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");
有关更多信息,请参见关系数据库建模-索引文档主题。
For more information, see Relational Database Modeling - Indexes documentation topic.
这篇关于仅在EF Core中为“ true”创建唯一约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!