首页 > 解决方案 > EF Core 自定义复杂约束

问题描述

我有一种情况,我将简化为以下内容:给定一个与 TEntityType 具有外部关系的模型 TEntity:

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 的约束。如何使用模型构建器进行配置?如何配置有关其他属性/字段的更复杂的约束?

标签: c#entity-framework-coreef-code-first

解决方案


在多列上创建索引

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.


推荐阅读