Last active
August 29, 2015 14:14
-
-
Save angularsen/b2d365a0078c9eadec19 to your computer and use it in GitHub Desktop.
Update pattern for MVC + Dal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[HttpPost] | |
[ValidateAntiForgeryToken] | |
public async Task<ActionResult> Edit(EditFooVm vm) | |
{ | |
if (!ModelState.IsValid) | |
{ | |
SaveModelState(); | |
return RedirectToAction("Edit", new {id = vm.FooId}); | |
} | |
if (!await _auth.CheckAccessAsync(User, vm.FooId, AccessFlags.Update)) | |
{ | |
return HttpNotFound(MessageFooNotFoundOrNotAuthorized); | |
} | |
await _versions.UpdateAsync(vm.FooId, w => | |
{ | |
w.Label = vm.Label; | |
// ..and other properties exposed by FooDal.UpdateWhitelist | |
}); | |
return RedirectToAction("Index"); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public async Task UpdateAsync(Guid id, [NotNull] Action<UpdateWhitelist> update) | |
{ | |
if (update == null) throw new ArgumentNullException("update"); | |
Foo existing = await _db.Foos.FindAsync(id); | |
if (existing == null) | |
throw new NotFoundException("Foo not found. Id: " + id); | |
update(new UpdateWhitelist(existing)); | |
existing.LastModified = DateTimeOffset.UtcNow; | |
await _db.SaveChangesAsync(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Nested type of FooDal, in a separate file using partial class | |
public class UpdateWhitelist | |
{ | |
private readonly Foo _existing; | |
public UpdateWhitelist([NotNull] Foo existing) | |
{ | |
if (existing == null) throw new ArgumentNullException("existing"); | |
_existing = existing; | |
} | |
public string Label | |
{ | |
get { return _existing.Label; } | |
set { _existing.Label = value; } | |
} | |
// .. other white listed properties | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment