Reputation: 65
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;
How can I re-write this to be like:
var ET = tables[entityName].Properties[propertyName].MaxLength;
This is my complete method:
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;
}
How to do it, please.
[Edit]
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;
}
It has three para:
Regards to all.
Upvotes: 1
Views: 216
Reputation: 205759
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;
// ...
Upvotes: 1