开发者

How to find out field maximum length in Entity Framework in .NET 4?

开发者 https://www.devze.com 2022-12-25 06:24 出处:网络
According to this question, there\'s no built-in way in EF v1 to figure out the length of a field. Is开发者_运维技巧 there a built-in way to do so in the Entity Framework that ships with .NET 4, if so

According to this question, there's no built-in way in EF v1 to figure out the length of a field. Is开发者_运维技巧 there a built-in way to do so in the Entity Framework that ships with .NET 4, if so - how?


There is no new way to access the length of a property in EF 4.0. You still have to walk over the metadata - as shown in the accepted answer on the question you reference.


This acts:

using System;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Data.Metadata.Edm;
using System.Linq;
using System.Linq.Expressions;

namespace EfWidgets
{
    public class EntityWidgets
    {
        public static int GetMaxLength<TEntity>(ObjectContext oc, Expression<Func<TEntity, string>> property)
            where TEntity : EntityObject
        {
            var test = oc.MetadataWorkspace.GetItems(DataSpace.CSpace);

            if (test == null)
                return -1;

            Type entType = typeof(TEntity);
            string propertyName = ((MemberExpression)property.Body).Member.Name;

            var q = test
                .Where(m => m.BuiltInTypeKind == BuiltInTypeKind.EntityType)
                .SelectMany(meta => ((EntityType)meta).Properties
                .Where(p => p.Name == propertyName && 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.TypeUsage.Facets["MaxLength"].Value)
                .ToList();

            if (queryResult.Any())
            {
                int result = Convert.ToInt32(queryResult.First());
                return result;
            }
            return -1;
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号