插入记录时出现DbEntityValidationException

时间:2016-01-27 20:32:21

标签: c# entity-framework asp.net-mvc-4

很抱歉很长的帖子。我有这些表关系:

- Room has many-to-many relationship with Activity
- RoomActivity has one-to-many relationship with Room and Activity
- Item has many-to-many relationship with Part
- ItemPart has one-to-many relationship with Item and Part
- Stage has foreign key relationship to RoomActivity and ItemPart
- Submission has a foreign key relationship to Stage

我有一个Web应用程序,员工可以提交他们今天所做的事情,包括房间,活动,项目,部分,然后提交表格。

我的控制器:

public ActionResult Create()
{
  ViewBag.ActivityRejectCodeId = GetRejectCodesByActivity(0);
  ViewBag.Activities = GetActivities();
  ViewBag.Workstations = GetRooms();
  ViewBag.Platforms = GetItems();
  ViewBag.Parts = GetParts();
  return View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(WorkOrderSubmission workordersubmission)
{
  if (ModelState.IsValid)
  {
    var activityId = Int32.Parse(Request.Form["Stage.RoomActivity.Activity.Id"]);
    var workstationId = Int32.Parse(Request.Form["Stage.RoomActivity.Workstation.Id"]);
    var platformId = Int32.Parse(Request.Form["Stage.ItemPart.Platform.Id"]);
    var partId = Int32.Parse(Request.Form["Stage.ItemPart.Part.Id"]);

    var rs = (from ps in db.Stages
      join wa in db.RoomActivities on ps.RoomActivityId equals wa.Id
      join pp in db.ItemParts on ps.ItemPartId equals pp.Id
      where ps.RoomActivity.ActivityId == activityId 
        && ps.RoomActivity.RoomId == workstationId 
        && ps.ItemPart.ItemId == platformId 
        && ps.ItemPart.ItemId == partId
      select new { ps.Id }).FirstOrDefault();

    var stageId = rs.Id;

    workordersubmission.StageId = stageId;
    workordersubmission.SubmissionDate = DateTime.Now;

    // Error when saving here
    db.WorkOrderSubmissions.Add(workordersubmission);
    db.SaveChanges();

    return RedirectToAction("Index");
  }

  ViewBag.stageId = new SelectList(db.Stages.OrderBy(p => p.Name), "Id", "Name", workordersubmission.StageId);
  return View(workordersubmission);
}

public SelectList GetActivities()
{
  var results = (from ps in db.Stages
  join wa in db.RoomActivities on ps.RoomActivityId equals wa.Id
  join a in db.Activities on wa.ActivityId equals a.Id
  select new
  {
    Id = wa.ActivityId,
    Name = a.Name
  })
  .Distinct()
  .OrderBy(n => n.Name);

  return new SelectList(results, "Id", "Name");
}

我的观点:

<div class="editor-label">
  @Html.LabelFor(model => model.Stage.RoomActivity.Activity.Id, "Activity")
</div>
<div class="editor-field">
  @Html.DropDownListFor(model => model.Stage.RoomActivity.Activity.Id,
    (SelectList)ViewBag.Activities, "")
  @Html.ValidationMessageFor(model => model.Stage.RoomActivity.Activity.Id)
</div>

我收到以下错误(已更新):

Validation failed for entity [Part]. Validation errors:
Number: The Number field is required.

Validation failed for entity [Item]. Validation errors:
Name: The Name field is required.

Validation failed for entity [Activity]. Validation errors:
Name: The Name field is required.

Validation failed for entity [Room]. Validation errors:
Name: The Name field is required

为什么我会在Part,Item,Activity,Room上收到错误?我试图插入新的提交内容。

舞台模特:

public partial class Stage
{
    public Stage()
    {
        this.WorkOrderSubmissions = new HashSet<WorkOrderSubmission>();
    }

    public int Id { get; set; }
    public int RoomActivityId { get; set; }
    public int ItemPartId { get; set; }
    public string Description { get; set; }
    public string Name { get; set; }

    public virtual ItemPart ItemPart { get; set; }
    public virtual RoomActivity RoomActivity { get; set; }
    public virtual ICollection<WorkOrderSubmission> WorkOrderSubmissions { get; set; }
}

WorkOrderSubmission模型:

public partial class WorkOrderSubmission
{
    public int Id { get; set; }
    public int WorkOrderId { get; set; }
    public int StageId { get; set; }
    public System.DateTime SubmissionDate { get; set; }

    public virtual Stage Stage { get; set; }
    public virtual WorkOrder WorkOrder { get; set; }
}

1 个答案:

答案 0 :(得分:0)

您是否可以添加此代码以获取有关DbEntityValidationException的更多信息并显示它?

try
{
    db.SaveChanges();
}
catch (DbEntityValidationException e)
{
    string errorFormat = @"Validation failed for entity [{0}]. Validation errors:" + Environment.NewLine + @"{1}";
    var errorList = new List<String>();
    foreach (var entityValidationError in e.EntityValidationErrors)
    {
        var entityName = entityValidationError.Entry.Entity.GetType().Name;
        var errors = String.Join(Environment.NewLine, entityValidationError.ValidationErrors.Select(a => a.PropertyName + ": " + a.ErrorMessage));
        errorList.Add(String.Format(errorFormat, entityName, errors));
    }
    throw new Exception(String.Join(Environment.NewLine + Environment.NewLine, errorList) + Environment.NewLine, e);
}