I have a user-added "Identification" property which needs not to be duplicated. (different from the DB Id).
I have added the following method to my ViewModel:
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
GearContext db = new GearContext();
if (db.Items.Where(p => p.Identification == this.Identification).Count() > 0)
{
yield return new ValidationResult("Identification already in use, please chose a different one. ", new[] { "Identification" });
}
}
The problem is that this prevents me to edit my model. I would like this validation to happen only when a new entry is created, not on edit.
I have tried the following type of edit in my controller:
if (ModelState.IsValid)
{
var item = db.Items.Find(viewModel.ItemId);
Mapper.Map<ItemViewModel, Item>(viewModel, item);
if (TryUpdateModel(item, null, null, new string[] { "Identification" }))
{
db.SaveChanges();
return RedirectToAction("Index");
}
}
also tried without the "TryUpdateModel" at all (simple viewmodel => model and db.save).
I thought about implementing the validation method in my DB context instead and run it only on item.State == EntityState.Added but I believe I don't have access the the edited model properties there.