我使用EF4和一段代码来获取实体中MaxLength
的值,代码如下:
public static int? GetMaxLength(string entityTypeName, string columnName)
{
int? result = null;
using (fooEntities context = new fooEntities())
{
Type entType = Type.GetType(entityTypeName);
var q = from meta in context.MetadataWorkspace.GetItems(DataSpace.CSpace)
.Where(m => m.BuiltInTypeKind == BuiltInTypeKind.EntityType)
from p in (meta as EntityType).Properties
.Where(p => p.Name == columnName
&& p.TypeUsage.EdmType.Name == "String")
select p;
var queryResult = q.Where(p =>
{
bool match = p.DeclaringType.Name == entityTypeName;
if (!match && entType != null)
{
match = entType.Name == p.DeclaringType.Name;
}
return match;
}).Select(sel => sel.TypeUsage.Facets["MaxLength"].Value);
if (queryResult.Any())
{
result = Convert.ToInt32(queryResult.First());
}
return result;
}
}
但是,我升级到EF5后就出现了这个错误消息:
...fooEntities' does not contain a definition for 'MetadataWorkspace' and no
extension method 'MetadataWorkspace' accepting a first argument of type
'...fooEntities' could be found (are you missing a using directive or an assembly
reference?)
如何从EF5中获取元数据?
MaxLength
值。如果您没有在模型属性中注释长度,例如:[Column("SomeColumn", TypeName="varchar(10)")]
,则此代码仅返回property.TypeUsage.Facets["MaxLength"].Value
的最大值,这将导致转换异常。如果您想直接从数据库获取长度,即在此情况下的10
,请查看我的答案:https://stackoverflow.com/a/71330103/8644294 - Ash K