1

I have a nullable type Enum property in my entity with name Status.

         public class MyType
         {
           [Column("StatusId")]
           public Nullable<AccountPaymentType> Status{ get; set; }
         }

         modelBuilder
        .Entity<MyType>()
        .Property(e => e.Status)
        .HasConversion(new EnumToNumberConverter<Enum.Status, int>());

The converter fails if DB return null. How can I support it?

I saw that there is constructor in class EnumToNumberConverter as

 public EnumToNumberConverter([CanBeNullAttribute] ConverterMappingHints mappingHints = null);

But I dont know how to use it.

D J
  • 6,908
  • 13
  • 43
  • 75
  • https://stackoverflow.com/questions/44262314/how-can-i-make-ef-core-database-first-use-enums/48237275 – Dongdong Jan 17 '20 at 01:24
  • You could define it as `int?` and then create an unmapped `AccountPaymentType?` property that converts it back and forth. The main down side is that you have to use the mapped property within queries. – juharr Jan 17 '20 at 03:48
  • There is nothing wrong in the way you use the converter. Also it is the default converter for enums which would be used if you omit `HasConversion` call. What is the exact EF Core version and what exactly fails (operation, exception message/call stack)? – Ivan Stoev Jan 17 '20 at 07:29

1 Answers1

1

You can try this:

            public class MyType
             {
               [Column("StatusId")]
               public Nullable<AccountPaymentType> Status{ get; set; }
             }

             modelBuilder
            .Entity<MyType>()
            .Property(e => e.Status)
            .HasDefaultValue(AccountPaymentType.[YOUR_DEFAULT_VALUE])
            .HasConversion(new EnumToNumberConverter<Enum.Status, int>());
jalsh
  • 801
  • 6
  • 18