Field max length in Entity framework

asp.net-mvc entity-framework

Question

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

Accepted Answer

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;
    }

Popular Answer

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;
    }


Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why