![](/img/trans.png)
[英]How to solve the "String or binary data would be truncated.\r\nThe statement has been terminated." error?
[英]EF Exception: String or binary data would be truncated. The statement has been terminated.?
我已經閱讀了許多與此問題相關的帖子,但找不到答案。 我正在嘗試將大量數據從 Excel 加載到 SQL Server。 數以千計的記錄。 我得到這個例外:
字符串或二進制數據將被截斷。 該語句已終止。
顯然有些值超過了數據庫中的字段大小。 該錯誤來自 SQL Server AFIK。
我的問題 - 我怎么可能知道是什么記錄和什么字段值導致了這種情況?
EF 異常中沒有具體細節,除了我提到的那個。
任何幫助表示贊賞。
有人要代碼片段,其實很簡單,不是代碼的問題:
// employees is a List<Employee> collection loaded from Excel
using (var context = new Entities())
{
employees.ForEach(e => context.Employee.AddObject(e));
context.SaveChanges();
}
此外,建議的使用DbEntityValidationException (僅在 Entity Framework 5.0 中可用)的方法不起作用, catch塊沒有捕獲異常。
try
{
ImportData();
}
catch (DbEntityValidationException ex)
{
foreach (var item in ex.EntityValidationErrors)
{
//...
}
}
到目前為止,我找到的唯一解決方案是使用 SQL Server Profiler,並定義以下要監視的事件:
現在我可以看到電子郵件太長了。
catch (DbEntityValidationException ex)
{
foreach (var item in ex.EntityValidationErrors)
{
//... inspect here
}
}
您可以在 foreach 循環中找到您需要的信息。
希望有幫助。
你不能在那個級別。 SQL Server 拒絕整個查詢。
我會針對字符串大小、日期格式等的數據庫約束對數據添加一些預檢查。
或者,您可以在嘗試插入之前將原始數據中的每個字符串字段TRIM
為相應的字段大小。
您可以在保存前檢查數據,使用 EF 元數據,並引發適當的錯誤。
不確定具體的截斷,但這里有一個提示,當您收到一個異常提示您檢查 EntityValidationErrors 時。 通常在調試時它不會讓您看到該屬性(除非您已經有一個明確的捕獲)。 但是,您可以打開 quick watch 並輸入$exception
。 現在您應該能夠深入了解並找到該屬性。 您也可以只輸入以下內容:
(System.Data.Entity.Validation.DbEntityValidationException)$exception
private static string FindLongStrings(object testObject)
{
foreach (PropertyInfo propInfo in testObject.GetType().GetProperties())
{
foreach (ColumnAttribute attribute in propInfo.GetCustomAttributes(typeof(ColumnAttribute), true))
{
if (attribute.DbType.ToLower().Contains("varchar"))
{
string dbType = attribute.DbType.ToLower();
int numberStartIndex = dbType.IndexOf("varchar(") + 8;
int numberEndIndex = dbType.IndexOf(")", numberStartIndex);
string lengthString = dbType.Substring(numberStartIndex, (numberEndIndex - numberStartIndex));
int maxLength = 0;
int.TryParse(lengthString, out maxLength);
string currentValue = (string)propInfo.GetValue(testObject, null);
if (!string.IsNullOrEmpty(currentValue) && currentValue.Length > maxLength && lengthString!="max")
return testObject.GetType().Name + "." + propInfo.Name + " " + currentValue + " Max: " + maxLength;
}
}
}
return "";
}
foreach (object insert in dtx.GetChangeSet().Inserts)
{
string result = FindLongStrings(insert);
if (string.IsNullOrEmpty(result) == false)
{
responseBuilder.Append(result);
}
}
如果 responseBuilder 不為空,則它包含字段名稱、允許的長度和錯誤消息。
我遇到過兩次這個問題,問題是當 EF 在數據庫中創建表時,它會將varchar(1)
為字符串屬性,所以當我嘗試插入信息時,由於長度的原因是不可能的,我建議你檢查表中的字段
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.