Set decimal(16, 3) for a column in Code First Approach in EF4.3

Ali Foroughi picture Ali Foroughi · Jan 27, 2012 · Viewed 63.5k times · Source

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 ?

Answer

dknaack picture dknaack · Jan 27, 2012

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);
    }
}