要记住的一件事是查询如下
this.Bottles.Where(b => b.Default).Any())
将针对数据存储执行。它不会反映任何可能已在本地修改但尚未保存的实体的状态。调用 execute 方法并将 where 运算符应用于结果后
this.HourTypes.Where(h => h.DefaultType).Execute().Where(h => h.DefaultType).Any()
第二个 Where 将针对我们从数据存储返回的实体的本地版本执行。
为了解决您的问题,我认为您需要针对当前更改执行本地查询以及数据存储查询。我在下面包含了一些验证逻辑,我认为它们可以解决您的问题。
partial void Bottles_Validate(Bottle entity, EntitySetValidationResultsBuilder results)
{
// Only run the Default Bottle validation logic for Bottles that will be Default Bottle.
if ((entity.Details.EntityState == EntityState.Added
|| entity.Details.EntityState == EntityState.Modified)
&& entity.Details.Properties.IsDefault.IsChanged
&& entity.IsDefault)
{
// Query the current set of changes to ensure there are not multiple Default bottles in it.
bool hasMultipleNewOrModifiedDefaultBottles = this.Details.GetChanges()
.OfType<Bottle>()
.Any(e => (e.Details.EntityState == EntityState.Added
|| e.Details.EntityState == EntityState.Modified)
&& e.IsDefault
&& e != entity);
if (hasMultipleNewOrModifiedDefaultBottles)
{
results.AddEntityError("Only 1 default bottle can exist.");
}
else
{
// Grab the current Default Bottle from the data store if one exists and ensure it
// is still marked as the default. This needs to account for the scenarios in which
// the Bottle has been changed to no longer be marked as the Default
// and the scenario in which the Bottle is being deleted.
Bottle defaultPersistedBottle = this.Bottles.Where(b => b.IsDefault)
.SingleOrDefault();
if (defaultPersistedBottle != null
&& defaultPersistedBottle.IsDefault
&& defaultPersistedBottle.Details.EntityState != EntityState.Deleted)
{
results.AddEntityError("Only 1 default bottle can exist.");
}
}
}
}