Skip to content

Instantly share code, notes, and snippets.

@dieseltravis
Last active July 17, 2019 22:40
Show Gist options
  • Select an option

  • Save dieseltravis/f849d76455521f7d0c7ddccf58ed96c2 to your computer and use it in GitHub Desktop.

Select an option

Save dieseltravis/f849d76455521f7d0c7ddccf58ed96c2 to your computer and use it in GitHub Desktop.
get max length of db column using entity framework, use that to truncate the value
//using System;
//using System.Data.Entity.Core.Metadata.Edm;
//using System.Data.Entity.Infrastructure;
//using System.Linq;
//using System.Linq.Expressions;
public static int GetMaxLength<T>(Expression<Func<T, string>> column)
{
int result = -1;
var entType = typeof(T);
var columnName = ((MemberExpression)column.Body).Member.Name;
using (var objectContext = ((IObjectContextAdapter)new SieEntities()).ObjectContext)
{
var queryResult = objectContext.MetadataWorkspace.GetItems(DataSpace.CSpace)?
.Where(m => m.BuiltInTypeKind == BuiltInTypeKind.EntityType)
.SelectMany(meta => ((EntityType)meta).Properties
.Where(p => p.Name == columnName && p.TypeUsage.EdmType.Name == "String")
)
.Where(p => p.DeclaringType.Name == entType.Name && p.TypeUsage.Facets["MaxLength"].Value.GetType().Name != "Unbounded")
.Select(sel => sel.TypeUsage.Facets["MaxLength"].Value)
.ToList();
if (queryResult?.Any() ?? false)
{
result = Convert.ToInt32(queryResult.First());
}
}
return result;
}
public static string Truncate<T>(Expression<Func<T, string>> column, string newValue)
{
int max = GetMaxLength(column);
if (max > -1 && !string.IsNullOrEmpty(newValue) && newValue.Length > max)
{
newValue = newValue.Substring(0, max);
}
return newValue;
}
// example:
var news = new News()
{
Title = SieExtensions.Truncate<News>(n => n.Title, item.Title),
// max length of 128 or something
Name = SieExtensions.Truncate<News>(n => n.Name, item.Name),
};
db.News.Add(news);
db.SaveChanges();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment