![](/img/trans.png)
[英]EF6 Throws Exception for EntityValidationErrors When I Try to Update Entity
[英]EntityValidationErrors EF6 Update Records
我需要通過實體框架和Windows服務更新表內的記錄集。 我已經正常完成了,沒有任何錯誤,但是現在出現以下錯誤,
一個或多個實體的驗證失敗。 有關更多詳細信息,請參見'EntityValidationErrors'屬性。
當我檢查錯誤時,具有VARCHAR(12)屬性的Nic是其主要原因。 在使用Nic列使用VARCHAR(10)之前,我將其更新為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);
在創建記錄時,我沒有任何問題。 有人可以幫我嗎?
我認為您的問題是由於數據庫和模型之間的不匹配所致,請嘗試更新EF模型,然后一切都會正常。
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.