How to get the maximum line length from an EDMX model in code?

I created an EDMX object from the database with which I am programming.

I need to get input from a user and save it in a row in a database table. The problem is that I need to limit the length of the input lines to the width of the corresponding VARCHAR column in the database.

When I look at the model, I can clearly see in the properties window that the model knows the maximum length of the string, but I do not know how to access this data in the code.

If I want to write something like this:

Entities entities = new Entities();
myTable = entities.myTable.First();
if (userInput.length > myTable.columnA.MaxLength)
{
    // tell the user that the input is too long.
}
else
{
    myTable.columnA = userInput;
}

How do i write?

Update: I would like to indicate that the IObjectContextAdapaterone mentioned in the answers below is in the namespace System.Data.Entity.Infrastructure.

+4
2

, :

int? GetMaxLength(DbContext context, string tableName, string propertyName)
{
    var oc = ((IObjectContextAdapter)context).ObjectContext;

    return oc.MetadataWorkspace.GetItems(DataSpace.CSpace).OfType<EntityType>()
             .Where(et => et.Name == tableName)
             .SelectMany(et => et.Properties.Where(p => p.Name == propertyName))
             .Select (p => p.MaxLength)
             .FirstOrDefault();
}

int? GetMaxLength<T>(DbContext context, Expression<Func<T, object>> property)
{
    var memberExpression = (MemberExpression)property.Body;
    string propertyName = memberExpression.Member.Name;
    return GetMaxLength(context, typeof(T).Name, propertyName);
}

, , , .

MetaData MaxLength.

+7

; edmx - , Microsoft ( ). context - DBC-.

var objectContext = ((IObjectContextAdapter)context).ObjectContext;
var entityType = objectContext.MetadataWorkspace.GetItems<EntityType>(DataSpace.CSpace).Where(e => e.Name == "your entity name").First();
var facets = entityType.Properties["your property name"].TypeUsage.Facets;

facets , MaxLength Name ( ) Value:

Count = 5
    [0]: Nullable=false
    [1]: DefaultValue=null
    [2]: MaxLength=250
    [3]: Unicode=false
    [4]: FixedLength=false
+1

All Articles