【发布时间】:2014-04-05 04:44:33
【问题描述】:
我正在使用 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 获取元数据的最佳方式是什么?
【问题讨论】:
-
我遇到了与 EF5 相关的程序集引用的各种问题。您是否尝试过使用包管理器控制台再次卸载和安装 EF5?这解决了我之前的一些问题。确保对解决方案中的所有项目执行此操作。可能值得一试。
-
这是一个全新安装的 VS2012 和一个全新的项目。我从旧项目中引入代码
-
注意:它不会带来来自数据库列的
MaxLength值。如果您没有在模型属性中注释长度,例如:[Column("SomeColumn", TypeName="varchar(10)")],则此代码仅返回 Max forproperty.TypeUsage.Facets["MaxLength"].Value,这会使其遇到 Cast 异常。如果您想要长度,即10在这种情况下直接来自数据库,请在此处查看我的答案:stackoverflow.com/a/71330103/8644294
标签: c# asp.net-mvc-4 entity-framework-5