I'm using EF Core with database-first approach using the "Scaffold-DbContext"-command to generate my DbContext / Entities.
How can I instruct Scaffold-DbContext that a certain field in a certain table should generate code to use an Enum instead of just an int?
This is how you used to do it in regular EF: https://www.devu.com/cs-asp/lesson-69-mapping-enum-types-entity-properties-framework-designer/
This enum is already defined in code:
public enum StateEnum { Ok = 1, Fail = 2 }
This is what Scaffold-DbContext gives me
public partial class Foo { public int Id { get; set; } public int State { get; set; } }
This is what I want it to create:
public partial class Foo { public int Id { get; set; } public StateEnum State { get; set; } }
Code-First is mainly useful in Domain Driven Design. In the Code-First approach, you focus on the domain of your application and start creating classes for your domain entity rather than design your database first and then create the classes which match your database design.
The default value of Enum constants starts from 0 and increments. It has fixed set of constants and can be traversed easily. However you can still change the start index and customize it with the value of your choice. In the following example, I have set the customized value to be 20 instead of the default 0.
By keeping the enum in your database, and adding a foreign key on the table that contains an enum value you ensure that no code ever enters incorrect values for that column. This helps your data integrity and is the most obvious reason IMO you should have tables for enums.
Doesn't value conversion in EF Core 2.1 do what you need now?
https://docs.microsoft.com/en-us/ef/core/modeling/value-conversions
Quick Example:
entity.Property(e => e.MyEnumField) .HasMaxLength(50) .HasConversion( v => v.ToString(), v => (MyEnum)Enum.Parse(typeof(MyEnum),v)) .IsUnicode(false);
Starting with Entity Framework Core 2.1, EF supports Value Conversions to specifically address scenarios where a property needs to be mapped to a different type for storage.
Specifically for Enums, you can use the provided EnumToStringConverter
or EnumToNumberConverter
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With