public async Task <AuthorizationResult> AuthorizeEntityChangeAsync(IIdentity user, DbEntityEntry ent) { if (ent.State == EntityState.Unchanged || ent.State == EntityState.Detached) { return(AuthorizationResult.Success()); } if (ent.Entity is T) { var casted = ent.Cast <T>(); switch (ent.State) { case EntityState.Added: var interpreted = Interpret.BeforeCreate(casted.Entity, GetContextInfo(user)); return((await Authorize.CreateAsync(interpreted, GetContextInfo(user))).CreateAggregateResult()); case EntityState.Modified: var original = CreateWithValues(casted.OriginalValues); var modified = CreateWithValues(casted.CurrentValues); var modifiedInterpreted = Interpret.BeforeModify((T)original, (T)modified, GetContextInfo(user)); foreach (var field in ent.CurrentValues.PropertyNames) { ent.CurrentValues[field] = modifiedInterpreted.GetType().GetProperty(field) .GetValue(modifiedInterpreted, null); } return((await Authorize.ModifyAsync((T)original, modifiedInterpreted, GetContextInfo(user))) .CreateAggregateResult()); case EntityState.Deleted: return((await Authorize.RemoveAsync( (T)CreateWithValues(casted.OriginalValues, casted.Entity.GetType()), GetContextInfo(user))) .CreateAggregateResult()); default: return(AuthorizationResult.Fail("The entity state is invalid", casted.Entity)); } } else { return(await GetChildRepositoryFor(ent).AuthorizeEntityChangeAsync(user, ent)); } }