c# - 仅在 EF Core 中为 'true' 创建唯一约束

标签 c# sql-server entity-framework-core

我有一个用于跟踪记录附件的类。每个 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 每个记录的值。

基本上我需要对 RecordIdIsPrimary == 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/

相关文章:

c# - 如何在 .NET Core 上正确实现 kafka 消费者作为后台服务

c# - 在 MVC3 中,是否可以在不同区域使用相同的 Controller 名称?

c# - 为存储过程调用实现线程池

asp.net-mvc - 使用 Entity Framework 7 和 SQL Server 2008 进行分页

c# - 调用MySql Table时自定义DataGridview宽度

c# - 使用 Entity Framework 检索许多嵌套实体的性能缓慢

sql-server - SQL Server 2008 - FileStream - 禁用文件的 8.3 名称和上次访问时间

sql-server - 在 Azure 自动化 powershell 脚本中从 SQL 打印消息不起作用

c# - 是否有任何可能的方法来连接来自使用 2 个不同 DbContexts 的 2 个不同数据库的 2 个表?

c# - ASP.NET Core 2.2 在 DbContext 中获取 userId