[Decimal(p, s)] attribute for EntityFramework Core.
$ dotnet add package Toolbelt.EntityFrameworkCore.DecimalAttribute.AttributeThis class library for Entity Framework Core on .NET Core/.NET Framework provides the ability for you to control the precision and scale of decimal column type, by annotating properties of entity types, like this.
[Decimal(10, 5)] // <-- This!
public decimal Height { get; set; }
Toolbelt.EntityFrameworkCore.DecimalAttribute package to your project.> dotnet add package Toolbelt.EntityFrameworkCore.DecimalAttribute
| The version of EF Core | Version of this package |
|---|---|
| v.3.1, 5, 6, 7, 8, 9, and 10 | v.5.0.1 or later (recommended), v.5.0, v.3.1 |
| v.3.0 | v.5.0.1 or later (recommended), v.5.0, v.3.1, v.3.0 |
| v.2.0, 2.1, 2.2 | v.1.0.x |
[Decimal(precision, scale)] attribute that lives in Toolbelt.ComponentModel.DataAnnotations.Schema.V5 namespace.using Toolbelt.ComponentModel.DataAnnotations.Schema.V5;
public class Person
{
public int Id { get; set; }
[Decimal(10, 5)] // <- Here!
public decimal Height { get; set; }
}
OnModelCreating() method of your DbContext class, and call BuildDecimalColumnTypeFromAnnotations() extension method which lives in namespace.Toolbelt.ComponentModel.DataAnnotationsusing Microsoft.EntityFrameworkCore;
using Toolbelt.ComponentModel.DataAnnotations;
public class MyDbContext : DbContext
{
...
// Override "OnModelCreating", ...
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// .. and invoke "BuildDecimalColumnTypeFromAnnotations"!
modelBuilder.BuildDecimalColumnTypeFromAnnotations();
}
}
That's all!
BuildDecimalColumnTypeFromAnnotations() extension method scans the DbContext with .NET Reflection technology, and detects [Decimal] attributes, then build models related to decimal column type.
After doing that, decimal type columns in the database which created by EF Core, is configured with precisions and scales that are specified by [Decimal] attribute.
To upgrade an existing project that uses ver.3 or before to use ver.5 or later of this package:
PM> Update-Package Toolbelt.EntityFrameworkCore.DecimalAttribute
using Toolbelt.ComponentModel.DataAnnotations.Schema;, and insert using Toolbelt.ComponentModel.DataAnnotations.Schema.V5; instead....
// 👇 Remove this line...
// using Toolbelt.ComponentModel.DataAnnotations.Schema;
// 👇 Insert this line, instead.
using Toolbelt.ComponentModel.DataAnnotations.Schema.V5;
...
If you want to use only "DecimalAttribute" class without any dependencies, you can use Toolbelt.EntityFrameworkCore.DecimalAttribute.Attribute NuGet package.