if you are using linq for sql why not try something like this
add a rule violation class to eliminate rule violations
public class RuleViolation { public string ErrorMessage { get; private set; } public string PropertyName { get; private set; } public RuleViolation(string errorMessage) { ErrorMessage = errorMessage; } public RuleViolation(string errorMessage, string propertyName) { ErrorMessage = errorMessage; PropertyName = propertyName; } }
now in your data class
[Bind(Exclude="ID")] public partial class Something { public bool IsValid { get { return (GetRuleViolations().Count() == 0); } } public IEnumerable<RuleViolation> GetRuleViolations() { if (String.IsNullOrEmpty(Name.Trim())) yield return new RuleViolation("Name Required", "Name"); if (String.IsNullOrEmpty(LocationID.ToString().Trim())) yield return new RuleViolation("Location Required", "LocationID"); yield break; } partial void OnValidate(ChangeAction action) { if (!IsValid) throw new ApplicationException("Rule violations prevent saving"); } }
and in your controller methods for updating, use the updatemodel method to change the properties
Something something = somethingRepo.GetSomething(id); try { //update something UpdateModel(something); somethingRepo.Save(); return RedirectToAction("Index"); } catch { ModelState.AddRuleViolations(something.GetRuleViolations()); return View(something); }
that way you can just add rules to your data class as it changes and it will appear in your updates, etc.
Jimmy source share