Entity framework field length limit

asp.net-mvc entity-framework

Question

Using ASP.NET MVC and the Entity Framework, I need to add a maximum length to my test field on my views, but I can't figure out how to retrieve the maximum length of a varchar field.

Is there a simple method to get that or any other database field property?

1
23
3/15/2011 8:06:20 PM

Accepted Answer

The following is how I do it (using 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;
    }
37
6/26/2012 9:37:04 AM

Popular Answer

Update

I am aware that this solution doesn't specifically deal with EF. There hadn't been any responses for around 20 minutes when I responded, so I reasoned that sharing my experience with LINQToSQL to address a similar issue could be helpful. It seems that I made the correct decision since the OP essentially used the same strategy, but using EF characteristics. For perspective and for anybody who get here with the same issue but a LINQToSQL query, I'm leaving this response here.

Original

In contrast to EF, ColumnAttributes are used to adorn LINQToSQL entity attributes. By looking at the CustomAttributesCollection, you may be able to get the ColumnAttribute from the PropertyInfo for the property. This attribute's value would need to be analyzed to determine its length. I implement it in my validator classes to ensure that using a string that is too lengthy for my column won't result in a SQL error.

I retrieve the column length for string characteristics using this technique.

    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 Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow