entity framework 5 MaxLength

前端 未结 4 1543
灰色年华
灰色年华 2020-12-28 17:47

I was using EF4 and a piece of code I found to get the MaxLength value from an entity like this:

public static int? GetMaxLength(string entityTy         


        
4条回答
  •  一向
    一向 (楼主)
    2020-12-28 18:39

    I refactored mccow002's example into a copy-paste-ready Extension method class:

    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    using System.Data.Metadata.Edm;
    
    public static class DbContextExtensions
    {
    
        // get MaxLength as an extension method to the DbContext
        public static int? GetMaxLength(this DbContext context, Expression> column)
        {
            return (int?)context.GetFacets(column)["MaxLength"].Value;
        }
    
        // get MaxLength as an extension method to the Facets (I think the extension belongs here)
        public static int? GetMaxLength(this ReadOnlyMetadataCollection facets)
        {
            return (int?)facets["MaxLength"].Value;            
        }
    
        // just for fun: get all the facet values as a Dictionary 
        public static Dictionary AsDictionary(this ReadOnlyMetadataCollection facets) {
            return facets.ToDictionary(o=>o.Name,o=>o.Value);
        }
    
    
        public static ReadOnlyMetadataCollection GetFacets(this DbContext context, Expression> column)
        {
            ReadOnlyMetadataCollection result = null;
    
            var entType = typeof(T);
            var columnName = ((MemberExpression)column.Body).Member.Name;
    
            var objectContext = ((IObjectContextAdapter)context).ObjectContext;
            var test = objectContext.MetadataWorkspace.GetItems(DataSpace.CSpace);
    
            if (test == null)
                return null;
    
            var q = test
                .Where(m => m.BuiltInTypeKind == BuiltInTypeKind.EntityType)
                .SelectMany(meta => ((EntityType)meta).Properties
                .Where(p => p.Name == columnName && p.TypeUsage.EdmType.Name == "String"));
    
            var queryResult = q.Where(p =>
            {
                var match = p.DeclaringType.Name == entType.Name;
                if (!match)
                    match = entType.Name == p.DeclaringType.Name;
    
                return match;
    
            })
                .Select(sel => sel)
                .FirstOrDefault();
    
            result = queryResult.TypeUsage.Facets;
    
            return result;
    
        }
    
    }
    

提交回复
热议问题