How can I edit an entity in MVC4 with EF5 which has a unique constraint?

Posted by Yoeri on Stack Overflow See other posts from Stack Overflow or by Yoeri
Published on 2012-09-12T09:37:05Z Indexed on 2012/09/12 9:37 UTC
Read the original article Hit count: 277

[HttpPost]
        public ActionResult Edit(Car car)
        {
            if (ModelState.IsValid)
            {
                db.Entry(car).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(car);
        }

This is a controller method scaffolded by MCV 4 My "car" entity has a unique field: LicensePlate. I have custom validation on my Entity:

Validation:

public partial class Car
    {
        partial void ValidateObject(ref List<ValidationResult> validationResults)
        {
            using (var db = new GarageIncEntities())
            {
                if (db.Cars.Any(c => c.LicensePlate.Equals(this.LicensePlate)))
                {
                    validationResults.Add(
                        new ValidationResult("This licenseplate already exists.", new string[]{"LicensePlate"}));
                }
            }
        }
    }

should it be usefull, my car entity:

 public partial class Car:IValidatableObject
    {
        public int Id { get; set; }
        public string Color { get; set; }
        public int Weight { get; set; }
        public decimal Price { get; set; }
        public string LicensePlate { get; set; }
        public System.DateTime DateOfSale { get; set; }
        public int Type_Id { get; set; }
        public int Fuel_Id { get; set; }

        public virtual CarType Type { get; set; }
        public virtual Fuel Fuel { get; set; }



        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
            {
                var result = new List<ValidationResult>();
                ValidateObject(ref result);
                return result;
            }

        partial void ValidateObject(ref List<ValidationResult> validationResults);
    }

QUESTION:

Everytime I edit a car, it raises an error:

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

The error is the one raised by my validation, saying it can't edit because there is already a car with that license plate.

If anyone could point me in the right direction to fix this, that would be great! I searched but couldn't find anything, so even related posts are welcome!

© Stack Overflow or respective owner

Related posts about validation

Related posts about asp.net-mvc-4