【发布时间】:2017-08-23 04:07:15
【问题描述】:
我正在使用 EF Core(在 ASP.NET Core 中,我的 DbContext 存在于每个请求/范围内)。
我的Employee 实体有这个属性:
public bool? IsBoss { get; set; }
还有这个配置:
entityBuilder.Property(b => b.IsBoss).IsRequired(false);
entityBuilder.HasIndex(b => b.IsBoss).IsUnique();
这会创建一个过滤索引,因此只能有一个真,一个假,但可以有多个空值。
我的应用要求我始终只有一名员工使用IsBoss==true。
假设我想调换两名员工。
employee1.IsBoss = null;
employee2.IsBoss = true;
context.SaveChanges();
这会引发唯一的约束冲突异常。
我可以通过将其包装在事务中来解决此问题:
using (var transaction = context.BeginTransaction())
{
try
{
employee1.IsBoss = null;
context.SaveChanges();
employee2.IsBoss = true;
context.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
}
}
我的问题是:为什么第一种方法会失败?我认为 EF Core automatically wraps 事务中的所有内容。为什么我必须使用事务?
【问题讨论】:
标签: .net entity-framework transactions entity-framework-core unique-constraint