I have an auto-generated entity framework Entity Data Model Designer File (edmx). And while I am using Data Annotations for validation purposes, there are times when retrieving the maxlength of an entity property programmatically would be very useful.
In some cases, I may want to simply truncate the value, rather than throw an error if the maxlength of a property is exceeded. Or I may want to surface the maxlength property to the client for client-side validation purposes.
It turns out to be a simple query, but it took me a while to find it. You will need to reference the following libraries:
using System.Data.Objects.DataClasses;
using System.Data.Metadata.Edm;
This is the method to retrieve the MaxLength property. Please note that you may get an exception if the property does not have a MaxLength property specified.
public static int? GetMaxLength(this EntityObject entityObject, string entityProperty)
{
CATDBEntities _context = new CATDBEntities();
int? result = null;
using (_context)
{
var q = from meta in _context.MetadataWorkspace.GetItems(DataSpace.CSpace)
.Where(m => m.BuiltInTypeKind == BuiltInTypeKind.EntityType)
from p in (meta as EntityType).Properties
.Where(p => p.DeclaringType.Name == entityObject.GetType().Name
&& p.Name == entityProperty
&& p.TypeUsage.EdmType.Name == "String")
select p;
var queryResult = from meta in _context.MetadataWorkspace.GetItems(DataSpace.CSpace)
.Where(m => m.BuiltInTypeKind == BuiltInTypeKind.EntityType)
from p in (meta as EntityType).Properties
.Where(p => p.DeclaringType.Name == entityObject.GetType().Name
&& p.Name == entityProperty
&& p.TypeUsage.EdmType.Name == "String")
select p.TypeUsage.Facets["MaxLength"].Value;
if (queryResult.Count() > 0)
{
result = Convert.ToInt32(queryResult.First());
}
}
return result;
}
To call this method, simply instantiate the entity object and pass in the proper parameters:
project _project = new project();
int? maxLength = DataAnnotation.GetMaxLength(_project, "project_name");