Results 1 to 2 of 2

Thread: MVC Create Error:EntityValidationErrors

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Oct 2006
    Posts
    719

    MVC Create Error:EntityValidationErrors

    I have this on my Module

    Module
    Code:
        public class Person
        {
            public int ID { get; set; }
            [Required]
            [StringLength(30)]
            public string First { get; set; }
            [Required]
            [StringLength(30)]
            public string Last { get; set; }
            public DateTime BirthDate { get; set; }
        }
    
        public class PersonContext : DbContext
        {
            public DbSet<Person> People { get; set; }
        }
    and this on Controller

    Controller
    Code:
            // GET: /Person/Create
    
            public ActionResult Create(Person person)
            {
                db.People.Add(person);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
    Every type I click the Create link, I'm encountering this error:

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

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: MVC Create Error:EntityValidationErrors

    You have validation attributes on the properties of your entity but your code is assuming that those attributes will never be violated. You need to check ModelState.IsValid to see whether the data entered by the user passes validation and only save it if it does. If it doesn't you need to redisplay the Create view with the validation errors so that the user can correct them.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width