I was using EF4 and a piece of code I found to get the MaxLength
value from an entity like this:
public static int? GetMaxLength(string entityTy
This is a very handy piece of code. I refactored it a bit and it's so useful I thought I would post it here.
public static int? GetMaxLength(Expression> column)
{
int? result = null;
using (var context = new EfContext())
{
var entType = typeof(T);
var columnName = ((MemberExpression) column.Body).Member.Name;
var objectContext = ((IObjectContextAdapter) context).ObjectContext;
var test = objectContext.MetadataWorkspace.GetItems(DataSpace.CSpace);
if(test == null)
return null;
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;
}
}
And you can call it like:
GetMaxLength(x => x.CustomerName);
This is assuming you've got a DbSet defined in your DbContext of type Customer, which has a property of CustomerName with a defined MaxLength.
This is very helpful for things like creating Model attributes that set a textbox's maxlength to the max length of the field in the database, always ensuring the two are the same.