Recently we had a task when we had a database with limited varchar length. Example:
TaskId int not null
TaskName nvarchar(5) null
Description nvarchar(50) null
We have data coming from this table from multiple sources and sometimes data overflows the fields. In entity framework if you try to assign value to taskName that is larger than 5 characters it will fail with “Entity Validation Failed”
for example:
task.TaskName ="MyLongTaskName";
ctx.SaveChanges();
Now, in our case we wanted to substring all values to fit in the field without throwing an exception.
so, in our example we wanted to have TaskName=”MyLon”
Since we are using EF6.1.3 it was possible to utilize EF interceptors to do this.
Below is the full code for Entity Framework interceptor that will truncate/trim all of the strings to the max size of a column. Just create a separate file and it should work.
You will also need to modify configuration to use this interceptor.
public class MyConfiguration : DbConfiguration
{
public MyConfiguration()
{
AddInterceptor(new StringTrimmerInterceptor());
}
}
public class StringTrimmerInterceptor : IDbCommandTreeInterceptor
{
private static readonly string[] _typesToTrim = {"nvarchar", "varchar", "char", "nchar"};
public void TreeCreated(DbCommandTreeInterceptionContext interceptionContext)
{
if (interceptionContext.OriginalResult.DataSpace == DataSpace.SSpace)
{
var insertCommand = interceptionContext.Result as DbInsertCommandTree;
if (insertCommand != null)
{
List<DbModificationClause> finalSetClauses =
new List<DbModificationClause>(
(IEnumerable<DbModificationClause>) insertCommand.SetClauses.Select(
a =>
{
var dbSetClause = a as DbSetClause;
if (dbSetClause != null)
{
var dbPropertyExpression = dbSetClause.Property as DbPropertyExpression;
if (dbPropertyExpression != null)
{
var edmProperty = dbPropertyExpression.Property as EdmProperty;
if (edmProperty != null && edmProperty.MaxLength != null &&
_typesToTrim.Contains(edmProperty.TypeName))
{
var dbConstantExpression = dbSetClause.Value as DbConstantExpression;
if (dbConstantExpression != null && dbConstantExpression.Value != null)
{
var value = dbConstantExpression.Value.ToString();
if (!string.IsNullOrEmpty(value) &&
value.Length > (int) edmProperty.MaxLength)
{
return DbExpressionBuilder.SetClause(
DbExpressionBuilder.Property(
DbExpressionBuilder.Variable(
insertCommand.Target.VariableType,
insertCommand.Target.VariableName),
dbPropertyExpression.Property.Name),
EdmFunctions.Trim(
dbConstantExpression.Value.ToString()
.Substring(0, (int) edmProperty.MaxLength)));
}
}
}
}
}
return a;
}));
var newInsertCommand = new DbInsertCommandTree(
insertCommand.MetadataWorkspace,
insertCommand.DataSpace,
insertCommand.Target,
new ReadOnlyCollection<DbModificationClause>(finalSetClauses),
insertCommand.Returning);
interceptionContext.Result = newInsertCommand;
}
}
var updateCommand = interceptionContext.Result as DbUpdateCommandTree;
if (updateCommand != null)
{
List<DbModificationClause> finalSetClauses =
new List<DbModificationClause>(
(IEnumerable<DbModificationClause>) updateCommand.SetClauses.Select(
a =>
{
var dbSetClause = a as DbSetClause;
if (dbSetClause != null)
{
var dbPropertyExpression = dbSetClause.Property as DbPropertyExpression;
if (dbPropertyExpression != null)
{
var edmProperty = dbPropertyExpression.Property as EdmProperty;
if (edmProperty != null && edmProperty.MaxLength != null &&
_typesToTrim.Contains(edmProperty.TypeName))
{
var dbConstantExpression = dbSetClause.Value as DbConstantExpression;
if (dbConstantExpression != null && dbConstantExpression.Value != null)
{
var value = dbConstantExpression.Value.ToString();
if (!string.IsNullOrEmpty(value) &&
value.Length > (int) edmProperty.MaxLength)
{
return DbExpressionBuilder.SetClause(
DbExpressionBuilder.Property(
DbExpressionBuilder.Variable(
updateCommand.Target.VariableType,
updateCommand.Target.VariableName),
dbPropertyExpression.Property.Name),
EdmFunctions.Trim(
dbConstantExpression.Value.ToString()
.Substring(0, (int) edmProperty.MaxLength)));
}
}
}
}
}
return a;
}));
var newInsertCommand = new DbUpdateCommandTree(
updateCommand.MetadataWorkspace,
updateCommand.DataSpace,
updateCommand.Target,
updateCommand.Predicate,
new ReadOnlyCollection<DbModificationClause>(finalSetClauses),
updateCommand.Returning);
interceptionContext.Result = newInsertCommand;
}
}