简体   繁体   中英

how to use EnumToNumberConverter for nullable enum

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.

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>());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM