Pomelo.EntityFrameworkCore.MySql icon indicating copy to clipboard operation
Pomelo.EntityFrameworkCore.MySql copied to clipboard

Support setting scaffold to use DateTimeOffset for all date types.

Open johnwc opened this issue 3 years ago • 7 comments

Requesting a feature request to have dotnet ef dbcontext scaffold have a option to use DateTimeOffset for all date types instead of DateTime.

johnwc avatar Nov 14 '21 02:11 johnwc

You could probably achieve that with Entity Framework Core Scaffolding with Handlebars.

mguinness avatar Nov 14 '21 05:11 mguinness

I looked at that first, I didn't see a way of mapping DB types to language types.

johnwc avatar Nov 14 '21 08:11 johnwc

Create an issue on that repo to see if what you're trying to do is possible, they seem pretty responsive.

mguinness avatar Nov 14 '21 16:11 mguinness

I was able to do it with Handlebars via a property transformer within ScaffoldingDesignTimeServices. Sample of code below. Would be nice though to not have to rely on yet another tool to do something so lite like this.

services.AddHandlebarsTransformers(
    propertyTransformer: (e) =>
    {
        if (e.PropertyType == "DateTime")
            e.PropertyType = nameof(DateTimeOffset);
        else if (e.PropertyType == "DateTime?")
            e.PropertyType = $"{nameof(DateTimeOffset)}?";

        return e;
    });

johnwc avatar Nov 18 '21 04:11 johnwc

We have implemented scaffolding customizations in the past, and this one makes a lot of sense to me.

lauxjpn avatar Nov 23 '21 01:11 lauxjpn

EF team just announced Database scaffolding templates for EF7 with documentation.

mguinness avatar Dec 16 '21 18:12 mguinness

Would be nice though to not have to rely on yet another tool to do something so lite like this.

@johnwc This can be achieved without any additional tools by registering a type mapping source plugin through a design time services class:

public class CustomMySqlDesignTimeServices : MySqlDesignTimeServices
{
    public override void ConfigureDesignTimeServices(IServiceCollection serviceCollection)
    {
        base.ConfigureDesignTimeServices(serviceCollection);

        serviceCollection.AddScoped<IRelationalTypeMappingSourcePlugin, CustomTypeMappingSourcePlugin>();
    }
}

public class CustomTypeMappingSourcePlugin : IRelationalTypeMappingSourcePlugin
{
    public RelationalTypeMapping FindMapping(in RelationalTypeMappingInfo mappingInfo)
        => mappingInfo.ClrType is null &&
           string.Equals(mappingInfo.StoreTypeNameBase, "datetime", StringComparison.OrdinalIgnoreCase)
            ? new MySqlDateTimeOffsetTypeMapping("datetime").Clone(mappingInfo)
            : null;
}

EF Core will discover the CustomMySqlDesignTimeServices class via reflection before scaffolding.

lauxjpn avatar Jan 03 '22 19:01 lauxjpn