【问题标题】:Error when saving Email using .SaveChanges();使用 .SaveChanges() 保存电子邮件时出错;
【发布时间】:2025-12-16 17:05:02
【问题描述】:

当我将电子邮件留空并提交注册表时,它会将表单输入正确保存到数据库中。但是,当我包含一封电子邮件(例如:testemail@gmail.com)时,它会在 db.SaveChanges(); 时产生验证错误;被调用。

我收到的错误是:

EntityFramework.dll 中出现“System.Data.Entity.Validation.DbEntityValidationException”类型的异常,但未在用户代码中处理

附加信息:一个或多个实体的验证失败。有关详细信息,请参阅“EntityValidationErrors”属性。

控制器:

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);
    }

型号:

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; }
}
}

查看:

@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")
}

【问题讨论】:

  • 向我们展示您收到的错误的详细信息。没有它,它几乎可以是任何东西。
  • 复制过去你在执行 db.savechanges() 时遇到的异常
  • 如果同时删除[RegularExpression("^[...")]@Html.ValidationMessageFor(m =&gt; m.email),它会保存电子邮件地址吗?
  • 我添加了上面错误的详细信息并添加了一个 try catch 块,它给了我:System.Data.Entity.Validation.DbEntityValidationResult
  • 我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。

标签: c# asp.net asp.net-mvc


【解决方案1】:

如果您提供的值大于该字段,则会发生这种情况;那是我通常明白的时候。但是,您可以通过捕获异常并检查其错误消息列表来获取所有错误:

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

在那里放一个断点,它会给你错误。

【讨论】:

  • 我添加了这部分代码,它给了我:System.Data.Entity.Validation.DbEntityValidationResult
【解决方案2】:
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);
                    }
                }
            } 

response.write 中的代码将为您提供属性名称和详细的错误消息。当您的用户输入大于数据库中字段的大小时,就会发生这种情况。

【讨论】:

    最近更新 更多