I was using EF4 and a piece of code I found to get the MaxLength
value from an entity like this:
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;
}
}
However, I upgraded to EF5 and I know get this error message:
...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?)
What's the best way to get that meta data from EF5?
This is a very handy piece of code. I refactored it a bit and it's so useful I thought I would post it here.
And you can call it like:
This is assuming you've got a DbSet defined in your DbContext of type Customer, which has a property of CustomerName with a defined MaxLength.
This is very helpful for things like creating Model attributes that set a textbox's maxlength to the max length of the field in the database, always ensuring the two are the same.
It means that you have not only upgraded EF but you have also changes the API. There are two APIs - the core ObjectContext API and simplified DbContext API. Your code is dependent on ObjectContext API (the only API available in EF4) but EF5 uses DbContext API (added in separate EntityFramework.dll assembly since EF4.1). If you want to use new EF features and your previous code you should just upgrade to .NET 4.5.
If you also want to use a new API you will have to update a lot of your existing code but it is still possible to get
ObjectContext
fromDbContext
and make your method work again. You just need to use this snippet:and use
objectContext
instead ofcontext
in your code.I had similar issue and solution is here;
I refactored mccow002's example into a copy-paste-ready Extension method class: