Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Field max length in Entity framework

Tags:

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

like image 860
moi_meme Avatar asked Apr 14 '09 19:04

moi_meme


People also ask

What is DataAnnotations MaxLength attribute?

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.

Which of the following attributes validate string length?

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.

What is System ComponentModel DataAnnotations?

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.

What is MaxLength in HTML?

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.


2 Answers

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;     } 
like image 128
moi_meme Avatar answered Sep 18 '22 15:09

moi_meme


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;     } 
like image 38
2 revs Avatar answered Sep 19 '22 15:09

2 revs