Fine-tuning Decimal Precision and Scale in EF Code First
Entity Framework (EF) Code First defaults to decimal(18, 0)
for System.Decimal
properties when mapping to SQL Server. However, you often need more control over precision and scale. Older methods involving direct EntityPropertyConfiguration
manipulation are now obsolete, superseded by a more streamlined approach in EF 4.1 and later.
Leveraging DecimalPropertyConfiguration.HasPrecision
The DecimalPropertyConfiguration
class provides the HasPrecision
method for precise control. Its syntax is:
<code class="language-csharp">public DecimalPropertyConfiguration HasPrecision(byte precision, byte scale)</code>
precision
: The total number of digits (before and after the decimal point).scale
: The number of digits after the decimal point.Practical Example: Setting Precision and Scale
Within your DbContext
class's OnModelCreating
method, you can specify precision and scale:
<code class="language-csharp">public class EFDbContext : DbContext { protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<MyClass>().Property(e => e.MyDecimalProperty).HasPrecision(12, 10); base.OnModelCreating(modelBuilder); } }</code>
This maps MyDecimalProperty
(of type decimal
) in the MyClass
entity to a SQL Server decimal(12, 10)
column. This ensures the database stores numbers with a maximum of 12 digits, with up to 10 decimal places.
The above is the detailed content of How Can I Control Precision and Scale for Decimal Properties in EF Code First?. For more information, please follow other related articles on the PHP Chinese website!