EF Core自定义复杂约束

问题描述

我将简化为以下情况:给定模型TEntity与TEntityType有外部关系:

public class TEntity
{
    public int TEntityTypeId TypeId { get; set; }
    public string Name { get;set; }
}

现在,当我想在数据库中插入TEntity的新实例时,我希望有一个约束,即名称在同一类型中是唯一的 。在代码中,如果要插入实例toBeInserted,请检查:

var conflictingEntity = await _repository.FindAsync(entity => entity.Name == toBeInserted.name && entity.TypeId == toBeInserted.TypeId );
if (conflictingEntity)
{
    // Don't insert record but,e.g.,throw an Exception
}

现在,我还想将该逻辑作为对DB Itelf的约束。如何使用模型构建器进行配置?如何配置有关其他属性/字段的更复杂的约束?

解决方法

在多列上创建索引

public class SampleContext : DbContext
{
    public DbSet<Patient> Patients { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Patient>()
            .HasIndex(p => new { p.Ssn,p.DateOfBirth})
            .IsUnique();
    }
}
public class Patient
{
    public int PatientId { get; set; }
    public string Ssn { get; set; }
    public DateTime DateOfBirth { get; set; }
}

查看此处:https://www.learnentityframeworkcore.com/configuration/fluent-api/hasindex-method

还有一点,请勿尝试在插入之前进行搜索。在多用户系统中,完全有可能另一个用户在搜索之后但在插入之前插入了一条记录。只需插入您的记录并处理DbUpdateException

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...