Open rkaushik15 opened 1 year ago
Type mappings can be altered via a type mapping plugin (e.g. NodaTime, spatial...), and of course by your database provider. There's no easy public API for tweaking the mappings from user code, although you can always extend your provider's IRelationalTypeMappingSource, making your changes there and replacing the service.
Can you please provide some context on exactly what you're doing to do, and why you need to change the default type mappings?
The database table we want to scaffold has some low-precision NUMERIC columns (for example, NUMERIC(1,0)). These are by default scaffolded to CLR Type 'decimal'. We are thinking if it would be possible to optimize this model by using smaller datatype such as short, byte, etc.
Can the new Custom Reverse Engineering Template feature in efcore 7 be useful for such a scenario?
@rkaushik15 Yes, the T4 template can be used to do this. Just scaffold the CLR type that you want and include the store type in the mapping or as an annotation.
@ajcvickers thanks for the confirmation! Is there any sample you can point me to which uses the T4 template and would implement this type CLR type overriding based on Store type?
Here's an example. In the default "EntityType.T4" template at around line 98 where each property is being written out:
// Change the CLR type based on whatever information about the property is relevant
var clrType = (property.Name == "Id" && property.GetColumnType() == "int")
? typeof(long)
: property.ClrType;
// Now use the clrType...
usings.AddRange(code.GetRequiredUsings(clrType));
var needsNullable = Options.UseNullableReferenceTypes && property.IsNullable && !clrType.IsValueType;
var needsInitializer = Options.UseNullableReferenceTypes && !property.IsNullable && !clrType.IsValueType;
#>
public <#= code.Reference(clrType) #><#= needsNullable ? "?" : "" #> <#= property.Name #> { get; set; }<#= needsInitializer ? " = null!;" : "" #>
<#
firstProperty = false;
@ajcvickers Thanks for providing the sample! :)
For migrations, the default type mappings can be overridden by using the HasColumnType() Fluent API. With this, a particular property will be mapped to the Store Type provided by the application, if the CLR type is compatible (even if by default that CLR type is mapped to some other Store Type)
Is there some provision for customizing the type mapping for a given Store Type to a specific CLR type while scaffolding?