根据this问题,EF v1中没有内置方法来计算字段的长度。是否有内置方法在.NET 4附带的实体框架中执行此操作,如果是这样 - 如何?
答案 0 :(得分:7)
在EF 4.0中没有新的方法来访问属性的长度。您仍然需要遍历元数据 - 如图in the accepted answer on the question you reference所示。
亚历克斯詹姆斯前EF团队成员!
答案 1 :(得分: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;
}
}
}