How can I make EF Core database first use Enums?
Solution 1
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
.
Solution 2
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);
Solution 3
I got here because of the question title. Not sure if this works in the "Scaffold-DbContext" but it does in DbContext (Microsoft.EntityFrameworkCore 2.0.1.0) by setting the base type of the enum explicitly even if the default underlying type of enumeration elements is int. You can use Fluent API to set default values with it too (especially this case where the enum starts with 1).
public enum StateEnum : int
{
Ok = 1,
Fail = 2
}
The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.
So I think this would work for any of these. enum (C# Reference)
public class MyDbContext : DbContext
{
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Foo>().Property(x => x.State).HasDefaultValue(StateEnum.Ok);
}
}
Solution 4
Currently, EF core does not support enums. Code like this:
public class MyDbContext : DbContext
{
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<StateEnum>(e => {...});
}
}
does not compile with the message:
CS0452 C# The type must be a reference type in order to use it as parameter 'TEntity' in the generic type or method
Solution: you can use enumeration classes instead
Solution 5
Try this solution:
public enum StateEnum {
Ok = 1,
Fail = 2
}
public partial class Foo
{
public int Id { get; set; }
public int StateId { get; set; }
public StateEnum State
{
get => (StateEnum)StateId;
set => StateId = (int)value;
}
}

Bassebus
Updated on April 17, 2021Comments
-
Bassebus about 2 years
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; } }