从MetadataWorkspace读取MaxLength [英] Reading MaxLength from MetadataWorkspace

查看:153
本文介绍了从MetadataWorkspace读取MaxLength的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一种从 MetadataWorkspace 读取的方法。试图读取特定的字段MaxLength。它运作良好
但是,不能将其更改为可以调用的方法,问题是:

I found a way here to read from MetadataWorkspace. Tried to read just specific field MaxLength. It worked well. But, Can't change it to work as a method that I can call, and the problem is that:

var tables = workspace.GetItems<EntityType>(DataSpace.SSpace);

返回完整的实体,我必须知道索引号到所需的一个,我可以'使用名称!。

return the complete entities, and I have to know the index number to the required one, I can't use the name!.

var ET = tables[4].Properties[propertyName].MaxLength;

我如何重写如下:

var ET = tables[entityName].Properties[propertyName].MaxLength;

这是我的完整方法:

public int GetMaxLenth(string entityName, string propertyName)
{
    var context = new CmsDbContext();
    ObjectContext objContext = ((IObjectContextAdapter)context).ObjectContext;
     MetadataWorkspace workspace = objContext.MetadataWorkspace;

     var tables = workspace.GetItems<EntityType>(DataSpace.SSpace);
     var ET = tables[4].Properties[propertyName].MaxLength;
     return ET.Value;
}

请问如何做。

向Ivan Stoev致谢他的帮助。我转移到EF Core,代码变短了。我想帮助别人,这是它:

Thnaks to Ivan Stoev for his help. I moved to EF Core, and the code become shorter. I wish to help someone else, This is it:

public static int GetMaxLenth(DbContext context, string entityName, string propertyName)
{
    var tables = context.Model.GetEntityTypes();
    var table = tables.First(type => type.ClrType.Name == entityName);
    return table.FindProperty(propertyName).GetMaxLength() ?? -1;
}

它有三个para:


  1. DbContext的名称。

  2. 表名。

  3. 字段名称

对所有人都抱歉。

推荐答案

确切的预定义方法。最接近的是 MetadataWorkspace.GetType ,但它除了实体名称之外还需要命名空间名称。所以你必须诉诸一些传统的方法,例如LINQ First ,例如:

There is no exact predefined method for that. The closest is MetadataWorkspace.GetType, but it requires namespace name in addition to entity name. So you have to resort to some traditional method, like LINQ First for instance:

// ...
var table = tables.First(type => type.Name == entityName);
var ET = table.Properties[propertyName].MaxLength;
// ...

这篇关于从MetadataWorkspace读取MaxLength的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆