Field max length in Entity framework

前端 未结 3 1785
野性不改
野性不改 2020-12-08 08:18

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.

I

3条回答
  •  情书的邮戳
    2020-12-08 08:34

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

提交回复
热议问题