Ryguydg
Ryguydg

Reputation: 103

Error when saving Email using .SaveChanges();

When I leave the Email blank and submit the Registration Form, it saves the form inputs into the Database correctly. However, when I include an email (ex: [email protected]) it produces validation error when the db.SaveChanges(); is called.

The error I am receiving says:

An exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in EntityFramework.dll but was not handled in user code

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

Controller:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Mkq.Models;

namespace Mkq.Controllers
{
    public class TeacherController : Controller
    {
        private MkqDbEntities db = new MkqDbEntities();

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Register([Bind(Include="teacher_id,subscription_id,teacher_fname,teacher_lname,username,password,email,teacher_credNumber,teacher_credST")] Teacher teacher)
    {
        teacher.subscription_id = 1;
        teacher.teacher_credNumber = null;
        teacher.teacher_credST = null;
        if (ModelState.IsValid)
        {
            db.Teachers.Add(teacher);
            db.SaveChanges();     //Error occurs when submitted
            return View();
        }

        // If we got this far, something failed, redisplay form
        return View(teacher);
    }

Model:

namespace Mkq.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

public partial class Teacher
{
    public Teacher()
    {
        this.Quiz_info = new HashSet<Quiz_info>();
        this.Students = new HashSet<Student>();
    }

    [DisplayName("Teacher ID")]
    public int teacher_id { get; set; }
    [DisplayName("Subscription ID")]
    public int subscription_id { get; set; }
    [DisplayName("First Name")]
    public string teacher_fname { get; set; }
    [DisplayName("Last Name")]
    public string teacher_lname { get; set; }
    [DisplayName("Username")]
    public string username { get; set; }
    [DisplayName("Password")]
    public string password { get; set; }
    [RegularExpression("^[a-zA-Z0-9_\\.-]+@([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$", ErrorMessage = "E-mail is not valid")]
    [DisplayName("Email")]
    public string email { get; set; }
    [DisplayName("Credential Number")]
    public string teacher_credNumber { get; set; }
    [DisplayName("Credential")]
    public string teacher_credST { get; set; }

    public virtual ICollection<Quiz_info> Quiz_info { get; set; }
    public virtual ICollection<Student> Students { get; set; }
    public virtual Subscription Subscription { get; set; }
}
}

View:

@model Mkq.Models.Teacher
@{
    ViewBag.Title = "Teacher Registration";
}

<h2>@ViewBag.Title.</h2>

@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    <h4>Create a new account.</h4>
    <hr />
    @Html.ValidationSummary()
    <div class="form-group">
        @Html.LabelFor(m => m.teacher_fname, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.teacher_fname, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.teacher_lname, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.teacher_lname, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.username, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
           @Html.TextBoxFor(m => m.username, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.password, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.password, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.email, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.email, new { @class = "form-control" })
            @Html.ValidationMessageFor(m => m.email)
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" class="btn btn-default" value="Register" />
        </div>
    </div>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Upvotes: 0

Views: 6161

Answers (2)

Neo
Neo

Reputation: 111

try
{
  db.SaveChanges();
}

catch (DbEntityValidationException ex)
            {
                foreach (var entityValidationErrors in ex.EntityValidationErrors)
                {
                    foreach (var validationError in entityValidationErrors.ValidationErrors)
                    {
                        Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
                    }
                }
            } 

The code in the response.write will give you the property name and detailed error message. This happens when your user input is greater than the size of the field in the database.

Upvotes: 1

Brian Mains
Brian Mains

Reputation: 50728

That would happen if the value you are providing is larger than the field; that's when I commonly get that. However, you can get all of the errors by catching the exception, and checking its lists of error messages:

catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
   foreach (var e in ex.EntityValidationErrors)
   {
      //check the ErrorMessage property
   }
}

Put a breakpoint in there, and it will give you the error.

Upvotes: 7

Related Questions