2010-03-30 1 views

ответ

7

Нет нового способа доступа к длине объекта в EF 4.0. Вам все равно придется пройти через метаданные - как показано in the accepted answer on the question you reference.

Alex James

Бывший член команды EF!

+0

Это справедливо для EF 5? –

0

Это действует:

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

Пример использования: maxLength = GetMaxLength (northwindContext, Product => Product.QuantityPerUnit); –

+0

Это лучше, чем аналогичный (но более короткий) метод от http://stackoverflow.com/a/772556/52277? –

Смежные вопросы