Skip to content

Instantly share code, notes, and snippets.

@Termiux
Last active May 17, 2024 03:09
Show Gist options
  • Save Termiux/6115547 to your computer and use it in GitHub Desktop.
Save Termiux/6115547 to your computer and use it in GitHub Desktop.
Gets the Maximum Length of a column table in Entity Framework 5
/// <summary>
/// Gets the Maximum Length of a column table in Entity Framework 5
/// Original from SO:
/// http://stackoverflow.com/questions/12378186/entity-framework-5-maxlength/12964634#12964634
/// You need to add a reference to System.Linq.Expressions
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="column"></param>
/// <returns></returns>
public static int GetColumnMaxLength<T>(Expression<Func<T, string>> column)
{
int result = 0;
var modelContext = new Models.MyContext();///<=Your model context
var objectContext = ((IObjectContextAdapter)modelContext).ObjectContext;
using (objectContext)
{
var entType = typeof(T);
var columnName = ((MemberExpression)column.Body).Member.Name;
var test = objectContext.MetadataWorkspace.GetItems(DataSpace.CSpace);
if (test == null)
return 0;
var q = test
.Where(m => m.BuiltInTypeKind == BuiltInTypeKind.EntityType)
.SelectMany(meta => ((EntityType)meta).Properties
.Where(p => p.Name == columnName && p.TypeUsage.EdmType.Name == "String"));
var queryResult = q.Where(p =>
{
var match = p.DeclaringType.Name == entType.Name;
if (!match)
match = entType.Name == p.DeclaringType.Name;
return match;
})
.Select(sel => sel.TypeUsage.Facets["MaxLength"].Value)
.ToList();
if (queryResult.Any())
result = Convert.ToInt32(queryResult.First());
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment