【问题标题】:EF Core custom complex constraintEF Core 自定义复杂约束
【发布时间】:2020-09-03 12:47:44
【问题描述】:

我有一种情况,我将简化为以下内容:给定一个与 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-core ef-code-first


    【解决方案1】:

    在多列上创建索引

    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

    【讨论】:

    • 谢谢!我总是想将索引仅用于查找改进等,而不是强制数据约束,但它就像一个魅力。只是一个小修复:您应该在 HasIndex(...) 之后将 .IsUnique() 添加到构建器。
    猜你喜欢
    • 2017-11-17
    • 1970-01-01
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    • 2016-11-23
    • 1970-01-01
    相关资源
    最近更新 更多