一个或多个实体的验证失败 - SaveChanges部分

时间:2014-01-02 04:31:04

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

当代码转到SaveChanges部分时,我遇到此错误。我将验证文本框。

模型

 public class CustomerSupplierModels : DbContext
{
    public class Customer_Supplier
    {
        public int CustomerSupplierId { get; set; }
        [Required(ErrorMessage = "FirstName is required")]
        public string FirstName { get; set; }
     //Some code here
 }}

查看

    @foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.FirstName)
            @Html.ValidationMessageFor(modelItem => item.FirstName)

        </td>
      //Some code here
}

存储库

public int AddorUpdateCustomerSupplier(Customer_Supplier cs)
    {
        try
        {
            if (cs.CustomerSupplierId != 0)
            {
                context.Entry(cs).State = EntityState.Modified;
            }
            else
            {
                context.Customer_Supplier.Add(cs);
            }

        }
        catch (DbEntityValidationException dbEx)
        {
            foreach (var validationErrors in dbEx.EntityValidationErrors)
            {
                foreach (var validationError in validationErrors.ValidationErrors)
                {
                    Trace.TraceInformation("Class: {0}, Property: {1}, Error: {2}", validationErrors.Entry.Entity.GetType().FullName,
                                  validationError.PropertyName, validationError.ErrorMessage);
                }
            }
        }
        return context.SaveChanges();
    }

0 个答案:

没有答案