Our goal
To be able to use a tool that generates automatically all the models from our DB (MySQL
) with Null Safety
enabled (Nullable
Reference Types) and that lets us modify some properties' types and values without losing all the advantages from automatic generation. The DB fields cannot be changed.
Our current situation
We are using the ** Entity Framework scaffold
command** to generate our DB Models.
We are using a custom class extending HbsCSharpEntityTypeGenerator
from the Handlebars library to modify the properties' types (we are using this because we need to modify only properties from specific entities), and then using OnModelCreatingPartial(ModelBuilder modelBuilder)
to convert the values when reading/saving to the DB, an example:
public partial class ContextX
{
partial void OnModelCreatingPartial(ModelBuilder modelBuilder)
{
modelBuilder.Entity<EntityX>()
.Property(x => x.PropertyX)
.HasConversion(
// In our model this property is an int? but the DB doesn't allow nulls,
// in case of NULL we save 0 into the DB
x => x == null ? 0 : x,
// The DB field is int (using 0 as NULL), in case of 0 we set NULL in our model
x => x == 0 ? null : x);
}
}
The problem
As shown here, Entity Framework's
property converter is not called when the types are for example int
and int?
, meaning that a ValueConverter<int, string>
will be called every time we need to read/save to the DB, but a ValueConverter<int?, int>
won't.
Our main reason behind using this approach was to use Nullable types and proper values in our models instead of wrong placeholders (empty strings, zeros, wrong default dates, etc), any solution matching the above requirements would be nice.
Thank you in advance.