Developer tips: Entity Framework decimal precision and open code by default in Visual Studio
OCC’s knowledge-sharing programme includes an internal technical newsletter, where developers share recommendations and discoveries. Here are a couple of recent tips from software consultants Matthew Clarke and Adam Wiseman.
Decimal precision in Entity Framework – Matthew Clarke
Entity Framework is certainly a divisive technology and I’m firmly in the camp of “not convinced”. The aim is to allow developers to work purely in C# without caring about the underlying SQL databases and types – magic Microsoft voodoo will deal with that for you. C# has a much simpler set of numeric types to work with than SQL. In C# you have: decimal or decimal? But in SQL you need to be precise: Decimal(10,2), Decimal(20,4), Decimal(66,6). It had never occurred to me that this difference was significant because “magic”.
Have you ever wondered how Entity Framework maps those variable-precision decimal properties to a database type? I certainly hadn’t!
Well the answer, as I found out recently, is that they all become Decimal(18,2) and it silently truncates data without you knowing.
To make things even better, there’s no built-in way to define the precision on a per-column basis in your EF object, though you can define it in the OnModelCreating method as per the snippet I’ve ripped from the internet below:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
.Property(p => p.NameOfProperty)
.HasPrecision(9, 4); // or whatever your schema specifies
Open code-behind by default in Visual Studio – Adam Wiseman
Usually when I’m working on a ticket, I want to go straight to the code. Most form maintenance involves the code-behind instead of the visible components. However, if the codefile has a form, when you double-click the codefile, Visual Studio opens the form by default. There are ways to switch to code, but you have to do them every time:
• F7 can be used to switch to code from the form designer
• or you can right-click on the file and select View Code in Solution Explorer, but that is tedious if you’ve already moved your hands to the keyboard
To go straight to the code every time, by default, there’s this easy fix described on StackOverflow:
• right-click on a file and select "Open With..."
• select "CSharp Editor"
• click "Set as Default"
Leave a Reply