EntityValidationErrors EF6更新记录

时间:2017-06-29 11:26:41

标签: c# asp.net sql-server windows entity-framework

我需要通过实体框架和Windows服务更新表中的记录集。我没有任何错误地正常完成,但现在我遇到了错误,

一个或多个实体的验证失败。请参阅' EntityValidationErrors'财产了解更多详情。

当我检查错误时,具有VARCHAR(12)属性的 Nic 是主要原因。在我使用VARCHAR(10)获得 Nic 列之前,我将其更新为VARCHAR(12)。但是当我尝试输入字符串长度为12的值时,尽管表和模型设置为12个字符,但我得到了该错误。

有人知道这种奇怪行为的原因吗?

       public void UpdateCustomers()
    {
        try
        {
            CustomerLoyaltyContext newContext = new CustomerLoyaltyContext();
            List<Customer_Update> customers = this.GetUpdatedCustomers();
            foreach (var cu in customers)
            {
                var cst = newContext.Customers.Where(a => a.MembershipNumber == cu.MembershipNumber).FirstOrDefault();
                if (cst != null)
                {
                    cst.MobileNumber = cu.MobileNumber;
                    //updating other records including Nic

                    newContext.Customers.Add(cst);
                    newContext.Entry(cst).State = EntityState.Modified;
                    newContext.SaveChanges();

                    tus.WriteToFile("User by mobile" + "[ " + cu.MobileNumber + " ]" + " Updated : [ " + cu.MembershipNumber + " ]\n");
                }
                else
                {
                    tus.WriteToFile("User by mobile" + "[ " + cu.MobileNumber + " ]" + " not found : [ " + cu.MembershipNumber + " ]\n");
                }
            }
        }
        catch (Exception ex)
        {
            tus.WriteToFile("Error Occured");
        }
    }

我的模特有,

[MaxLength(12)]
public string Nic{get;set;}

和我的数据库Nic列也具有相同的属性,

我尝试将代码用于我的OnModelCreating方法,但没有做得更好,

Database.SetInitializer<MyContext>(null);

在创作的唱片中,我没有任何问题。有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

我认为您的问题是由于您的数据库与您的模型不匹配,请尝试更新您的EF模型,一切都应该没问题。

希望它有所帮助。