Question

How can I do this :

private decimal _SnachCount;
[Required]
[DataType("decimal(16 ,3")]
public decimal SnachCount
{
    get { return _SnachCount; }
    set { _SnachCount = value; }
}

private decimal _MinimumStock;
[Required]
[DataType("decimal(16 ,3")]
public decimal MinimumStock
{
    get { return _MinimumStock; }
    set { _MinimumStock = value; }
}

private decimal _MaximumStock;
[Required]
[DataType("decimal(16 ,3")]
public decimal MaximumStock
{
    get { return _MaximumStock; }
    set { _MaximumStock = value; }
}

After generating the database by this part of my model , these three columns type are decimal(18,2),why? what is this code error? how can i do that ?

Was it helpful?

Solution

The DataType Attribute is a Validation Attribute. You need to do that using the ModelBuilder.

public class MyContext : DbContext
{
    public DbSet<MyClass> MyClass;
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<MyClass>().Property(x => x.SnachCount).HasPrecision(16, 3);
        modelBuilder.Entity<MyClass>().Property(x => x.MinimumStock).HasPrecision(16, 3);
        modelBuilder.Entity<MyClass>().Property(x => x.MaximumStock).HasPrecision(16, 3);
    }
}

OTHER TIPS

You can modify all decimal propreties in database. In your DBContext in method OnModelCreating add line:

modelBuilder.Properties<decimal>().Configure(c => c.HasPrecision(18, 3));

This is copied from the answer I posted to the same question over here; https://stackoverflow.com/a/15386883/1186032.


I had a nice time creating an Custom Attribute for this:

[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public sealed class DecimalPrecisionAttribute : Attribute
{
    public DecimalPrecisionAttribute(byte precision, byte scale)
    {
        Precision = precision;
        Scale = scale;

    }

    public byte Precision { get; set; }
    public byte Scale { get; set; }

}

using it like this

[DecimalPrecision(20,10)]
public Nullable<decimal> DeliveryPrice { get; set; }

and the magic happens at model creation with some reflection

protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
    foreach (Type classType in from t in Assembly.GetAssembly(typeof(DecimalPrecisionAttribute)).GetTypes()
                                   where t.IsClass && t.Namespace == "YOURMODELNAMESPACE"
                                   select t)
     {
         foreach (var propAttr in classType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.GetCustomAttribute<DecimalPrecisionAttribute>() != null).Select(
                p => new { prop = p, attr = p.GetCustomAttribute<DecimalPrecisionAttribute>(true) }))
         {

             var entityConfig = modelBuilder.GetType().GetMethod("Entity").MakeGenericMethod(classType).Invoke(modelBuilder, null);
             ParameterExpression param = ParameterExpression.Parameter(classType, "c");
             Expression property = Expression.Property(param, propAttr.prop.Name);
             LambdaExpression lambdaExpression = Expression.Lambda(property, true,
                                                                      new ParameterExpression[]
                                                                          {param});
             DecimalPropertyConfiguration decimalConfig;
             if (propAttr.prop.PropertyType.IsGenericType && propAttr.prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
             {
                 MethodInfo methodInfo = entityConfig.GetType().GetMethods().Where(p => p.Name == "Property").ToList()[7];
                 decimalConfig = methodInfo.Invoke(entityConfig, new[] { lambdaExpression }) as DecimalPropertyConfiguration;
             }
             else
             {
                 MethodInfo methodInfo = entityConfig.GetType().GetMethods().Where(p => p.Name == "Property").ToList()[6];
                 decimalConfig = methodInfo.Invoke(entityConfig, new[] { lambdaExpression }) as DecimalPropertyConfiguration;
             }

             decimalConfig.HasPrecision(propAttr.attr.Precision, propAttr.attr.Scale);
        }
    }
}

the first part is to get all classes in the model (my custom attribute is defined in that assembly so i used that to get the assembly with the model)

the second foreach gets all properties in that class with the custom attribute, and the attribute itself so i can get the precision and scale data

after that i have to call

modelBuilder.Entity<MODEL_CLASS>().Property(c=> c.PROPERTY_NAME).HasPrecision(PRECITION,SCALE);

so i call the modelBuilder.Entity() by reflection and store it in the entityConfig variable then i build the "c => c.PROPERTY_NAME" lambda expression

After that, if the decimal is nullable i call the

Property(Expression<Func<TStructuralType, decimal?>> propertyExpression) 

method (i call this by the position in the array, it's not ideal i know, any help will be much appreciated)

and if it's not nullable i call the

Property(Expression<Func<TStructuralType, decimal>> propertyExpression)

method.

Having the DecimalPropertyConfiguration i call the HasPrecision method.

So, what I got working for me is this:

public class RestaurantItemEntity : BaseEntity
{
    [Column(TypeName = "VARCHAR(128)")]
    [StringLength(128)]
    [Required]
    public string Name { get; set; }


    [Column(TypeName = "VARCHAR(1024)")]
    [StringLength(1024)]
    public string Description { get; set; }


    [Column(TypeName = "decimal(16,2)")]
    [Required]
    public decimal Price { get; set; }


    [Required]
    public RestaurantEntity Restaurant { get; set; }
}

This is EF Code first for .NET core.

You can also set the precision of decimals using the code-first model mapping approach like this:

public class MyEntityMapping : EntityTypeConfiguration<MyEntity>
{
    public MyEntityMapping()
    {
        HasKey(x => x.Id);
        Property(x => x.Id).IsRequired();
        // .HasPrecision(precision, scale)
        // 'precision' = total number of digits stored,
        // regardless of where the decimal point falls 
        // 'scale' = number of decimal places stored
        Property(x => x.DecimalItem).IsRequired().HasPrecision(16, 6);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top