Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make EF Core database first use Enums?

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/

Example

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; } } 
like image 826
Bassebus Avatar asked May 30 '17 12:05

Bassebus


People also ask

How do I use code-first in Entity Framework Core?

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.

Where does enum start from?

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.

Should you use enums in database?

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.


2 Answers

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); 
like image 152
MrKobayashi Avatar answered Oct 15 '22 19:10

MrKobayashi


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.

like image 31
Dejan Avatar answered Oct 15 '22 19:10

Dejan