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 t
This is the same question answered at: Does EF7 support 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);
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);
}
}
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
You can have you enum (U) and an entity (T) representing enum values in the database
public static T[] BuildEntityObjectsFromEnum<T, U>() where U: Enum where T : new()
{
var listObjectsToReturn = new List<T>();
Dictionary<string, int> dictionary = Enum.GetValues(typeof(U)).Cast<U>().ToDictionary(t => t.ToString(), t => Convert.ToInt32(t));
foreach (var item in dictionary)
{
var newObject = new T();
Type classType = typeof(T);
classType.GetProperties()[0].SetValue(newObject, item.Value); // Enum int id
classType.GetProperties()[1].SetValue(newObject, item.Key); // Enum string value
listObjectsToReturn.Add(newObject);
}
return listObjectsToReturn.ToArray();
}
Then you can seed the table from the enum
modelBuilder.Entity<T>().HasData(BuildEntityObjectsFromEnum<T,U>());
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;
}
}