【问题标题】:EntityValidationErrors EF6 Update RecordsEntityValidationErrors EF6 更新记录
【发布时间】:2017-06-29 11:26:41
【问题描述】:

我需要通过实体框架和 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;}

我的数据库网卡列也具有相同的属性,

我尝试在 OnModelCreating 方法中使用以下代码,但没有得到任何改善,

Database.SetInitializer<MyContext>(null);

在创建记录时我没有任何问题。有人可以帮我解决这个问题吗?

【问题讨论】:

  • 换模后你$ update-database了吗?
  • 是,但在当前实施中没有。由于安全问题,我的客户端不允许将服务器连接到互联网,也不允许安装第三方应用程序。因此,我正在本地设置上进行所有迁移,并替换客户端服务器中的文件和整个数据库。

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


【解决方案1】:

我认为您的问题是由于您的数据库和模型不匹配造成的,请尝试更新您的 EF 模型,一切都会好起来的。

希望对你有帮助。

【讨论】:

  • 它有助于我的本地设置。从本地设置迁移后,我必须将托管服务器数据库替换为本地数据库。谢谢你的回复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-29
相关资源
最近更新 更多