c# - 在列上创建唯一约束

标签 c# asp.net-core entity-framework-core

我有这个型号

public class Record
{
    public int Id {get;set;}
    public int Client {get;set;}
    public bool IsActive {get;set;}
}

我想为 IsActive 列创建约束。

每个客户端只能有 1 条事件记录。

我如何在模型上实现这一目标?

最佳答案

您需要为 ef core 的列创建过滤索引 filter index功能,您可以使用重写的 OnModelCreating 方法在 dbcontext 中配置它。

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   modelBuilder.Entity<Record>(entity =>
   {
       entity.HasIndex(e => e.Client)
        .HasName("Record_Filtered_Index")
        .HasFilter("([IsActive]=(1))");
   });
}

关于c# - 在列上创建唯一约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56732108/

相关文章:

c# - 我有一些连接表混淆

asp.net - 如何在 .csproj 文件(而不是 project.json)中指定 ASP.NET Core 目标框架导入?

c# - Entity Framework Core - 一般设置值转换器

c# - 如何在 C# 中使用 MODI (Microsoft Office Document Imaging) 连续进行 OCR

c# - 如何以编程方式调用 Windows 权限对话框?

c# - Http 错误 404.13 ASP.NET Core MVC 的自定义错误页面

testing - 在集成测试中访问内存 dbcontext

c# - EF Core 有条件地启用延迟加载

c# - 在 EntityFrameworkCore 中更新一个稍微复杂的实体

c# - 在 asp.net core 3.0 中为角色 SecurityStamp 创建 ClaimsIdentityOptions