Reputation: 775
I'm currently working on upgrading an old Web API project and I'm trying to bring EF Core (5.0 preview) into the project instead of using old third-party libraries (a long story for another time). To help achieve this, I've been reverse engineering the database tables (using EF Core Power Tools).
Some of my tables have fields that can map to Enums. What I'm wondering is if there is a way I can change the datatype of a entity (e.g. from string to Enum) so that if I ran the Reverse Engineering option again, the change wouldn't be overwritten?
As an example, my table implementation looks like (pretty standard) ...
[Table("MyTable")]
public partial class MyTable
{
public string SomeProperty { get; set; }
}
How can I change the data type of SomeProperty
from string
to SomePropertyEnum
, but not have it overwritten if I do another 'Reverse Engineer' using EF Core Power Tools? Can I use another partial class, or would it have to done in a derived class?
I believe I would also need to make an adjustment in the DbContext file to accomodate this change (a Value Conversion??). If so, how can I handle that without it being overwritten?
Upvotes: 0
Views: 1124
Reputation: 775
In the end I decided to go down the path of just leaving my Entity classes and create a matching DTO class ... then use AutoMapper to do the conversion from string to Enum.
// EF Core generated table entity
[Table("MyTable")]
public partial class MyTable
{
public string SomeProperty { get; set; }
}
// DTO class to map to the table entity
public class MyTableAsDTO
{
public MyEnum SomeProperty { get; set; }
}
... then used AutoMapper to do the conversion:
CreateMap<MyTable, MyTableAsDTO>()
.AfterMap((src, dest) =>
{
if (Enum.TryParse(src.SomeProperty, out MyEnum myEnum)
dest.SomeProperty = myEnum;
else
dest.SomeProperty = MyEnum.<defaultValue>;
})
.ReverseMap();
Not sure if there is a more elegant way to do this, but this works for now. I can run the EF Core Power Tools 'Reverse Engineering' option, refresh my table entities, but not lose any custom data type changes.
UPDATE: As @LucianBargaoanu mentioned in the comments, I don't actually need to manually do the Enum conversion ... this is built-in to AutoMapper. So my mapping would simply look like ...
CreateMap<MyTable, MyTableAsDTO>()
.ReverseMap();
Upvotes: 0
Reputation: 11173
I think you could achieve what you want by replacing the IScaffoldingModelFactory service with your own that extends RelationalScaffoldingModelFactory.
Then I think you could override VisitColumn or maybe GetTypeScaffoldingInfo to manipulate the metadata of each column.
You'll also find some other ideas in this related question; Entity Framework Core Customize Scaffolding
Upvotes: 0