What's going on
This is basically what happens:
HTTP Request -> API Controller -> EF Core Query -> JSON Serialization -> HTTP Response
The crucial part is the JSON Serialization. This takes arbitrary data (in your case the result of an EF Core Query) and converts it to JSON. The JSON Serialization is called under the hood by the thing that is calling your API controller's method. It's done by System.Text.Json.JsonSerializer
due to the default configuration of ASP.Net core. In order to get 0.0
instead of 0.000000000
you have to change that configuration.
How to solve
To change the default JSON Serialization configuration of ASP.NET core you have to add some code to the ConfigureServices()
method in your Startup.cs
file:
// Inside Startup.cs
// Find services.AddControllers() and change it to
services
.AddControllers()
.AddJsonOptions(o => o.JsonSerializerOptions.Converters.Add(new MyDecimalConverter()));
The code above needs the MyDecimalConverter
class which you need to add to your project.
public class MyDecimalConverter : JsonConverter<Decimal>
{
public override Decimal Read(
ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options) =>
reader.GetDecimal();
public override void Write(
Utf8JsonWriter writer,
Decimal decimalValue,
JsonSerializerOptions options) =>
// taken from https://stackoverflow.com/a/7983330/4262276
writer.WriteNumberValue(decimalValue / 1.0000000000000000000000000000m);
}