TrackableEntities / EntityFrameworkCore.Scaffolding.Handlebars

Scaffold EF Core models using Handlebars templates.
MIT License
208 stars 53 forks source link

[Question] How to register multiple propertyTransformer #218

Closed stijndp closed 1 year ago

stijndp commented 1 year ago
        public void ConfigureDesignTimeServices(IServiceCollection services)
        {
            services.AddHandlebarsScaffolding();
            services.AddHandlebarsTransformers(propertyTransformer: p => p.PropertyType == "byte" ? new EntityPropertyInfo("int", p.PropertyName, p.PropertyIsNullable) : p);
            services.AddHandlebarsTransformers(propertyTransformer: p => p.PropertyType == "byte?" ? new EntityPropertyInfo("int?", p.PropertyName, p.PropertyIsNullable) : p);
        }

As I found out, this only registers the second transformer.

        public void ConfigureDesignTimeServices(IServiceCollection services)
        {
            services.AddHandlebarsScaffolding();
            services.AddHandlebarsTransformers(propertyTransformer: p => p.PropertyType == "byte" ? new EntityPropertyInfo("int", p.PropertyName, p.PropertyIsNullable) : p)
                .AddHandlebarsTransformers(propertyTransformer: (e, p) => p.PropertyType == "byte?" ? new EntityPropertyInfo("int?", p.PropertyName, p.PropertyIsNullable) : p);
        }

I found in the documentation the methods could be chained but this also only applies the last propertyTransformer.

It's the end of the day and my brain is fried so it's probably a simple answer but I couldn't find an example of use.

stijndp commented 1 year ago

Woke up and suddenly saw the forest through the trees.

services.AddHandlebarsTransformers(propertyTransformer: p => p.PropertyType == "byte" ? new EntityPropertyInfo("int", p.PropertyName, p.PropertyIsNullable) : p.PropertyType == "byte?" ? new EntityPropertyInfo("int?", p.PropertyName, p.PropertyIsNullable) : p);

Or to keep it readable for future self.

services.AddHandlebarsTransformers(propertyTransformer: p =>
{
    EntityPropertyInfo newEntityPropertyInfo;
    switch (p.PropertyType)
    {
        case "byte":
            newEntityPropertyInfo = new EntityPropertyInfo("int", p.PropertyName, p.PropertyIsNullable);
            break;
        case "byte?":
            newEntityPropertyInfo = new EntityPropertyInfo("int?", p.PropertyName, p.PropertyIsNullable);
            break;
        default:
            newEntityPropertyInfo = p;
            break;
    }
    return newEntityPropertyInfo;
});

Or maybe Oracle will fix their default scaffold mapping for ef core so number(3) and number(4) don't get mapped to byte in the future. It's only been an open issue for over 6 months.