I need to put a max length on my test field on my Views using ASP.NET MVC with the Entity Framework and I can't find how to get the max length of a varchar field.
Is there an easy way to get that, or any other property of a database field
Data Annotations - MaxLength Attribute in EF 6 & EF Core The MaxLength attribute specifies the maximum length of data value allowed for a property which in turn sets the size of a corresponding column in the database. It can be applied to the string or byte[] properties of an entity.
The StringLength Attribute Specifies both the Min and Max length of characters that we can use in a field. StringLength is somewhat similar to MaxLength and MinLength attribute but operates only on string type properties.
Data annotations (available as part of the System. ComponentModel. DataAnnotations namespace) are attributes that can be applied to classes or class members to specify the relationship between classes, describe how the data is to be displayed in the UI, and specify validation rules.
The maxlength attribute defines the maximum number of characters (as UTF-16 code units) the user can enter into an <input> or <textarea> . This must be an integer value 0 or higher. If no maxlength is specified, or an invalid value is specified, the input or textarea has no maximum length.
Here is how i manage to do it (with an extension method on entities) :
public static int? GetMaxLength(this EntityObject entite, string nomPropriete) { int? result = null; using (XEntities contexte = XEntities.GetCurrentContext()) { var queryResult = from meta in contexte.MetadataWorkspace.GetItems(DataSpace.CSpace) .Where(m => m.BuiltInTypeKind == BuiltInTypeKind.EntityType) from p in (meta as EntityType).Properties .Where(p => p.DeclaringType.Name == entite.GetType().Name && p.Name == nomPropriete && p.TypeUsage.EdmType.Name == "String") select p.TypeUsage.Facets["MaxLength"].Value; if (queryResult.Count() > 0) { result = Convert.ToInt32(queryResult.First()); } } return result; }
Update
I realize that this answer doesn't directly apply to EF. At the time that I answered, there had been no answers for about 20 minutes and I thought knowing how I solved a similar problem with LINQToSQL might help. Given that the OP basically used the same technique albeit with EF properties instead, seems to indicate that I made the right choice. I'm leaving this answer here for context and for those who get here having the same problem but with LINQToSQL.
Original
I don't know about EF, but LINQToSQL entity properties are decorated with ColumnAttributes. You may be able to get the ColumnAttribute from the PropertyInfo for the property by looking at the CustomAttributesCollection. The value of this attribute would need to be parsed for length. I do that in my validator classes to make sure that I'm not going to get a SQL error by using a string that is too long for my column.
This is the method I use to extract the column length for string properties.
public static int MaximumPropertyLength( Type type, string propertyName ) { int maximumLength = -1; PropertyInfo info = type.GetProperty( propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ); if (info != null) { var attribute = info.GetCustomAttributes( typeof( ColumnAttribute ), false ) .Cast<ColumnAttribute>() .FirstOrDefault(); if (attribute != null) { maximumLength = ExtractLength( attribute.DbType ); } } return maximumLength; } private static int ExtractLength( string dbType ) { int max = int.MaxValue; if (dbType.Contains( "(" )) { string[] parts = dbType.Split( new char[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries ); if (parts.Length > 1) { int.TryParse( parts[1], out max ); } } return max; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With