if you are using Linq to SQL why not try something like this
add a rule violations class to handle 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 on 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's methods for updating, use the updatemodel method for changing properties
Something something = somethingRepo.GetSomething(id);
try
{
//update something
UpdateModel(something);
somethingRepo.Save();
return RedirectToAction("Index");
}
catch
{
ModelState.AddRuleViolations(something.GetRuleViolations());
return View(something);
}
this way you can just add rules to your data class as it changes and it will be reflected in your updates, etc