如何使用实体框架更新数据库中的记录时覆盖模型验证

时间:2017-12-19 07:32:25

标签: asp.net-mvc entity-framework-6

我试图使用实体框架来更新我的数据库中的记录 问题是当我尝试更新记录时,我得到了dbEntity验证错误 因为我的模型上有[EmailAddress]验证,当我想要更新某些内容时,是否还要覆盖此验证?

模特:

public partial class T
{
    public int Id { get; set; }

    [Required]
    public string name { get; set; }
    public string lastname { get; set; }

    [Required]
    [EmailAddress]
    public string email { get; set; }
}

这是更新:

[HttpPost]
    public ActionResult UpdateR(int id, FormCollection collection)
    {
        try
        {
            var user = new T() { Id = id, email = "Deactivated"};
            using (var db = new Database1Entities())
            {
                db.T.Attach(user);
                db.Entry(user).Property(x => x.email).IsModified = true;
                db.SaveChanges();

                return RedirectToAction("Index");
            }


        }
        catch (Exception e)
        {
            ViewBag.message = e.ToString();
            return View();
        }
    }

和视图:

  <table id="mytable" class="table table-bordered table-striped">
  <thead>
  <tr>
      <th>@Html.DisplayNameFor(item => item.name)</th>
      <th>@Html.DisplayNameFor(item => item.lastname)</th>
      <th>@Html.DisplayNameFor(item => item.email)</th>
  </tr>
  </thead>
  <tbody>
  @foreach (var item in Model)
  {
      <tr>
          <td>@Html.DisplayFor(mitem => item.name)</td>
          <td>@Html.DisplayFor(mitem => item.lastname)</td>
          <td>@Html.DisplayFor(mitem => item.email)</td>
          <td>@Html.ActionLink("Update", "UpdateR", new { id = item.Id})
</td>
      </tr>
  }
  </tbody>
</table>

修改:

db.Configuration.ValidateOnSaveEnabled = false;

在db.SaveChanges()之前;如果有人有同样的问题,我会为我工作。

Ref

1 个答案:

答案 0 :(得分:1)

我将DbContextConfiguration.ValidateOnSaveEnabled Property更改为false。

[HttpPost]
public ActionResult UpdateR(int id, FormCollection collection)
{
    try
    {
        var user = new T() { Id = id, email = "Deactivated"};
        using (var db = new Database1Entities())
        {
            db.Configuration.ValidateOnSaveEnabled = false;
            db.T.Attach(user);
            db.Entry(user).Property(x => x.email).IsModified = true;
            db.SaveChanges();

            return RedirectToAction("Index");
        }


    }
    catch (Exception e)
    {
        ViewBag.message = e.ToString();
        return View();
    }
}