c# - 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 的约束。如何使用模型构建器进行配置?如何配置有关其他属性/字段的更复杂的约束?
解决方案
在多列上创建索引
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
.
推荐阅读
- swift - Swift:我可以(运行时检查)查找 CodingKey 的相应成员值吗?
- java - java - 如何通过在java中的空位置添加零来使两个不相等的二维数组相等?
- r - 提高 R for 循环的计算时间
- c# - 尝试压缩多个文件夹中的文件
- android - SimpleXMLConverter 和改造 2.30。为什么序列化会因 ValueRequiredException 而崩溃?
- angular - Angular5 ng-bootstrap,带点的轮播指示器
- http-post - 当查询字符串参数以字节形式在正文中发送时,服务器返回“无法连接到远程服务器”
- reactjs - 即使使用文档中的 ref 示例,“ref 也不是道具”
- java - 我的代码没有按预期工作。十进制输出不应该是
- java - 问题在 ec2 中部署类似 springboot 的服务