【问题标题】:How to find out field maximum length in Entity Framework in .NET 4?如何在 .NET 4 中找出实体框架中的字段最大长度?
【发布时间】:2010-03-30 13:25:42
【问题描述】:

根据this 的问题,EF v1 中没有内置方法来计算字段的长度。在 .NET 4 附带的实体框架中是否有 内置 方法可以做到这一点,如果有的话 - 怎么做?

【问题讨论】:

    标签: .net entity-framework .net-4.0 entity-framework-4


    【解决方案1】:

    在 EF 4.0 中没有访问属性长度的新方法。您仍然需要遍历元数据 - 如图所示 in the accepted answer on the question you reference

    【讨论】:

      【解决方案2】:

      这个行为:

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

      【讨论】:

      • 使用示例:maxLength = GetMaxLength(northwindContext, Product => Product.QuantityPerUnit);
      • 它是否比stackoverflow.com/a/772556/52277 的类似(但更短)方法更好?
      猜你喜欢
      • 1970-01-01
      • 2013-02-21
      • 1970-01-01
      • 1970-01-01
      • 2011-07-21
      • 1970-01-01
      • 2019-07-16
      • 2018-02-01
      相关资源
      最近更新 更多