[英]EF Core - String or binary data would be truncated
當您有 80(+/-) 列可供選擇時,您如何確定哪一列是罪魁禍首? 使用 .Net Core (netcoreapp2.2) 和 EF Core 2.2.4。
拿起一些現有的代碼,並嘗試跟蹤失敗的列。 但是,它不起作用。 我在這里和其他地方查看了數十個示例,但沒有找到在 EF Core 2.x 中執行此操作的方法。
public int GetColumnMaxLength(string table, EntityEntry entityEntry)
{
// Just a rough to get the right data - always returns 0 for the moment...
int result = 0;
var modelContext = entityEntry.Context;
var entityType = modelContext.Model.FindEntityType(table); // THIS IS ALWAYS NULL!
if (entityType != null)
{
// Table info
var tableName = entityType.Relational().TableName;
var tableSchema = entityType.Relational().Schema;
// Column info
foreach (var property in entityType.GetProperties())
{
var columnName = property.Relational().ColumnName;
var columnType = property.Relational().ColumnType;
var isFixedLength = property.Relational().IsFixedLength;
};
}
return result;
}
上面的代碼由圍繞 db.SaveAsync() 的 try/catch 的這個 catch 部分調用; 陳述。
catch (Exception ex)
{
// -----------------------------------------
// no idea what this was really trying to
// do as it barfs out all columns...
// -----------------------------------------
var dataInfo = new DataInfo();
var strLargeValues = new List<Tuple<int, string, string, string>>();
foreach (var entityEntry in _db.ChangeTracker.Entries().Where(et => et.State != EntityState.Unchanged))
{
// -----------------------------------------
// try to get the column info for all
// columns on this table...
// -----------------------------------------
dataInfo.GetColumnMaxLength("Subscription", entityEntry);
foreach (var entry in entityEntry.CurrentValues.Properties)
{
var value = entry.PropertyInfo.GetValue(entityEntry.Entity);
if (value is string s)
{
strLargeValues.Add(Tuple.Create(s.Length, s, entry.Name, entityEntry.Entity.GetType().Name));
}
}
}
var l = strLargeValues.OrderByDescending(v => v.Item1).ToArray();
foreach (var x in l.Take(100))
{
Trace.WriteLine(x.Item4 + " - " + x.Item3 + " - " + x.Item1 + ": " + x.Item2);
}
throw;
}
所以,問題的關鍵是:如何從 EF Core 獲取 SQL 列定義?
我希望能夠在incomingData.Length > targetColumnDefinition.Length
時記錄特定的表和列
最終解決方案:
public override int SaveChanges()
{
using (LogContext.PushProperty("DbContext:Override:Save", nameof(SaveChanges)))
{
try
{
return base.SaveChanges();
}
catch (Exception ex)
{
var errorMessage = String.Empty;
var token = Environment.NewLine;
foreach (var entityEntry in this.ChangeTracker.Entries().Where(et => et.State != EntityState.Unchanged))
{
foreach (var entry in entityEntry.CurrentValues.Properties)
{
var result = entityEntry.GetDatabaseDefinition(entry.Name);
var value = entry.PropertyInfo.GetValue(entityEntry.Entity);
if (result.IsFixedLength && value.ToLength() > result.MaxLength)
{
errorMessage = $"{errorMessage}{token}ERROR!! <<< {result.TableName}.{result.ColumnName} {result.ColumnType.ToUpper()} :: {entry.Name}({value.ToLength()}) = {value} >>>";
Log.Warning("Cannot save data to SQL column {TableName}.{ColumnName}! Max length is {LengthTarget} and you are trying to save something that is {LengthSource}. Column definition is {ColumnType}"
, result.TableName
, result.ColumnName
, result.MaxLength
, value.ToLength()
, result.ColumnType);
}
}
}
throw new Exception(errorMessage, ex);
}
}
}
正如評論中提到的,您需要全名,這可以從元數據中讀取。
public int GetColumnMaxLength(EntityEntry entityEntry)
{
int result = 0;
var table = entityEntry.Metadata.Model.FindEntityType(entityEntry.Metadata.ClrType);
// Column info
foreach (var property in table.GetProperties())
{
var maxLength = property.GetMaxLength();
// For sql info, e.g. ColumnType = nvarchar(255):
var sqlInfo = property.SqlServer();
};
return result;
}
在 .NET Core 3.1 和 EFCore 5.0.2 上,此日志記錄無需額外的擴展方法即可工作:
try
{
await context.SaveChangesAsync();
}
catch(Exception ex)
{
foreach (var entityEntry in context.ChangeTracker.Entries().Where(et => et.State != EntityState.Unchanged))
{
foreach (var entry in entityEntry.CurrentValues.Properties)
{
var prop = entityEntry.Property(entry.Name).Metadata;
var value = entry.PropertyInfo?.GetValue(entityEntry.Entity);
var valueLength = value?.ToString()?.Length;
var typemapping = prop.GetTypeMapping();
var typeSize = ((Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping) typemapping).Size;
if (typeSize.HasValue && valueLength > typeSize.Value)
{
Log.Error( $"Truncation will occur: {entityEntry.Metadata.GetTableName()}.{prop.GetColumnName()} {prop.GetColumnType()} :: {entry.Name}({valueLength}) = {value}");
}
}
}
throw ex;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.