【发布时间】: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