Decimal truncation on Database First Approach
Hi guys.
I had a problem with an project with Database First Approach. My app was truncating every decimal's information.
Consider model as:
class Sell
{
public int SellerId { get; set; }
public decimal Total { get; set; }
}
and Context as:
// This context was generated by 'dotnet ef scaffold' command
class MainContext
{
public DbSet<Sell> Sells { get; set; }
modelBuilder.Entity<Sell>(entity =>
{
entity.Property(e => e.Total)
.HasColumnType("DECIMAL")
.HasColumnName("TOTAL");
}
}
When I perform an insert/update operation, it just saves the integer part of decimal.
var sell = new Sell {
SellerId = 1.
Total = 323.99
};
context.Sells.Add(sell);
await context.SaveChangesAsync(); // It just saved 323
Looking for a solution I realized the problem was column type generated by ef scaffolding proccess. I adjusted my context as follows:
// This context was generated by 'dotnet ef scaffold' command
class MainContext
{
public DbSet<Sell> Sells { get; set; }
modelBuilder.Entity<Sell>(entity =>
{
entity.Property(e => e.Total)
.HasColumnType("NUMERIC(10, 3)")
.HasColumnName("TOTAL");
// I changed DECIMAL to NUMERIC with precision present on table's field.
}
}
I would like to ask to fix this issue and I give my problem and how I solved this problem.
Thanks in advance.
It seems the problem is in this method.
The current code is ignoring several metadata about the columns, like
- charset and collation (for string values)
- precision and scale (for numeric values)
-
DEFAULTvalues -
COMPUTED BYsources - attached sequences (generators)
@cincuranet with your approval I would like to start working on a PR to fix all this.
And also to add sequences (generators) support to scaffolding.
I already did a similar work on Firebird dialect for SQLAlchemy implementation. For reference, this is the metadata query we use.
Go ahead.
One last question: Should I branch it from ef7 branch? (say yes, please)
You can, but I do not promise that branch to be super stable.
Understood. No problems. 👍