0

I'm new to EF so apologies if my vocabulary is off!

How can I access the decimal precision of a field in my model? I want to validate incoming decimal data before I try and add it to make sure it's within the range of the SQL column? This is what I'm looking for:

Decimal member properties facet

I want to check against the model rather than a 'magic number' so that a change to the model doesn't necessitate a change in the validation code.

Solution (based on Paul Abbott's link in the comments):

/// <summary>
/// Returns precision and scale for a decimal-typed Property of an EntityType
/// </summary>
public static Tuple<int, int> GetDecimalPrecisionAndScale(DbContext context, string tableName, string columnName)
{
    var objectContext = ((IObjectContextAdapter)context).ObjectContext;
    var entityType = objectContext.MetadataWorkspace.GetItems<EntityType>(DataSpace.CSpace)
                        .Where(e => e.Name == tableName).First();
    var facets = entityType.Properties[columnName].TypeUsage.Facets;

    int precision = Convert.ToInt32(facets["Precision"].Value);
    int scale = Convert.ToInt32(facets["Scale"].Value);

    return new Tuple<int, int>(precision, scale);
}
technophebe
  • 494
  • 3
  • 13

0 Answers0