我试图在实体框架6中覆盖EnityFramework的DbContext.ValidateEntity()方法。
我遇到的问题是我需要在验证逻辑中调用FirstOrDefaultAsync(),但这会导致覆盖问题,因为该方法未标记为异步。这是我到目前为止的代码......
protected override DbEntityValidationResult ValidateEntity (
DbEntityEntry entityEntry, IDictionary<object, object> items)
{
var result = new DbEntityValidationResult(
entityEntry, new List<DbValidationError>());
if (entityEntry.Entity is Post && entityEntry.State == EntityState.Added)
{
Post post = entityEntry.Entity as Post;
// This line is illegal as the ValidateEntity()
// method is not asynchronous
var errors = await ValidatePost(post);
// error processing here..
}
if (result.ValidationErrors.Count > 0)
{
return result;
}
else
{
return base.ValidateEntity(entityEntry, items);
}
}
public async Task<ICollection<DbValidationError>>
ValidatePost(Post post)
{
var errors = new List<DbValidationError>();
Post temp = await this.DbContext.Posts
.FirstOrDefaultAsync(x => x.Title == entity.Title);
if ((temp != null) && (temp.Id != entity.Id))
{
errors.Add(new DbValidationError(
"Title", "A Post already exists with the title " + temp.Title
));
}
return errors;
}
上面显示的实际验证逻辑有些简化,但它证明了问题。
如何从ValidateEntity /非异步方法中调用.FirstOrDefaultsAsync()或任何实体框架异步方法?