Eidenai
Eidenai

Reputation: 441

Validation Failed For Required Entity That Doesn't Exist In Form?

So I've put down android for the time being and decided to get back to my .Net roots and get familiar with ASP/MVC. However, I'm currently having this issue:

I've created a simple log in form, and the model behind it has a userID but it's a key that I'm going to generate via code so it's not got the required tag. Problem is when I go to register I get this error:

Exception Details: System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. The validation errors are: The m_IdentityCode field is required.

There is however no attribute specifying it's requirement. I've watched a few videos where people used the [key] attribute and it didn't produce the requirement issue so I'm not sure what's going on and would appreciate any help.

[Key]
public string m_IdentityCode { get; set; }

Edit;

[HttpPost]
public ActionResult UserRegistration(UserAccountModel user)
{
    if (ModelState.IsValid)
    {
        using (AccountDatabaseContext context = new AccountDatabaseContext())
        {

            context.m_UserAccounts.Add(user);
            context.SaveChanges();

            ModelState.Clear();
            ViewBag.Message = "You have successfully registered your account. Welcome.";
        }
    }

    return View();
}

Upvotes: 2

Views: 392

Answers (1)

ocuenca
ocuenca

Reputation: 39326

Before add the user to your DbSet you need to set your Key property with a value:

    using (AccountDatabaseContext context = new AccountDatabaseContext())
    {
        user.m_IdentityCode="someValue";
        context.m_UserAccounts.Add(user);
        context.SaveChanges();
    }

Your issue is because that property by default is null, and when you call SaveChanges method, EF is going to validate your model and will notice you haven't set your key property.

Upvotes: 2

Related Questions