ASP .NET MVC — Set precision for Decimal for Entity Framework Code First

Jen-Hsuan Hsieh (Sean)
A Layman
Published in
3 min readAug 6, 2019

--

We found that the table only contained two decimal places and we want to save more place in the SQL server.

Introduction

For SQL Server, we have to decide the precision for the decimal type. For example, decimal(10, 3) means 7 integer place and 3 decimal place.

However, the precision for the C# code mapping to SQL Server is fixed to decimal(18, 2) when we use Entity Framework Code First.

The solution is quite simple.

Solution

There are 2 methods to solve this problem.

1. Set precision by using modelBuilder

The first method is to set precision by using modelBuilder.

2. Write customized convention

The disadvantage of the first method to solve this problem is that you have to remember to modify OnModelCreating(). An alternative way is to create a customized convention.

--

--

Jen-Hsuan Hsieh (Sean)
A Layman

Frontend Developer🚀 Angular • React • Nest • Electron • Micro-frontend • Monorepo Architecture • https://daily-learning.herokuapp.com/