Home >Backend Development >C++ >How Do I Control Decimal Precision and Scale in EF Core Code-First Migrations?

How Do I Control Decimal Precision and Scale in EF Core Code-First Migrations?

Susan Sarandon
Susan SarandonOriginal
2025-01-21 23:36:11728browse

How Do I Control Decimal Precision and Scale in EF Core Code-First Migrations?

Understanding Decimal Precision and Scale in EF Core Code-First Migrations

Entity Framework Core's Code-First approach requires careful consideration when mapping decimal properties to database columns. While the default mapping is decimal(18, 0) in SQL Server, you'll often need to customize the precision and scale for specific data requirements.

Defining Precision and Scale

To control the precision and scale of your decimal columns, leverage the HasPrecision method within the DecimalPropertyConfiguration class. This method accepts two arguments: precision (total number of digits) and scale (number of decimal places).

Illustrative Example:

<code class="language-csharp">public class EFDbContext : DbContext
{
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<MyClass>().Property(e => e.MyDecimalProperty).HasPrecision(12, 10);

        base.OnModelCreating(modelBuilder);
    }
}</code>

In this code snippet, MyDecimalProperty is configured with a precision of 12 and a scale of 10, allowing for a total of 12 digits with 10 places after the decimal point.

Important Considerations:

  • The HasPrecision method is not supported in older EF versions (e.g., EF 4.1). For these versions, use the HasColumnType method as shown below:

    <code class="language-csharp">  modelBuilder.Entity<MyClass>().Property(e => e.MyDecimalProperty).HasColumnType("decimal(12, 10)");</code>
  • Remember that precision represents the overall number of digits, while scale specifically refers to the digits following the decimal point.

The above is the detailed content of How Do I Control Decimal Precision and Scale in EF Core Code-First Migrations?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn