Does EF7 (EFCore) support enums?

entity-framework entity-framework-core

Question

I have problem with EF7 RC1 (EFCore). I am unable to work with enums in my model. I can save enum property. The value is casted to int. My problem is that during data reading i get invalid cast exception.

  1. Does EF7 support enum properties ?
  2. How can i configure it with fluent api ?

Thanks

EDIT:

enum:

  public enum LimitMode 
    {
        Max,
        Min,
        MaxAndMin,
    }

Model:

  public class SomeModel 
    {
    (..)
    public LimitMode LimitMode {get; set;}
    }

ModelBuilder for SomeModel:

        modelBuilder.Entity<SomeModel>(entity => {
            (...)
            entity.Property(p => p.LimitMode);
        })
1
6
5/1/2019 7:43:20 PM

Popular Answer

Value converters are now supported in EntityFrameworkCore 2.1 This allows you to treat Enums as strings in your database and have them correctly convert to Enums in your model.

You do this with a value converter. You can create your own but EF Core 2.1 comes with some pre-defined value converters out of the box. One of these is the EnumToString value converter.

So given the following:

public class Rider
{
    public int Id { get; set; }
    public EquineBeast Mount { get; set; }
}

public enum EquineBeast
{
    Donkey,
    Mule,
    Horse,
    Unicorn
}

Use the default converter like this:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder
        .Entity<Rider>()
        .Property(e => e.Mount)
        .HasConversion<string>();
}

Or if you prefer using attributes on your model classes like this:

public class Rider
{
    public int Id { get; set; }

    [Column(TypeName = "nvarchar(24)")]
    public EquineBeast Mount { get; set; }
}
2
6/6/2018 1:41:29 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow