Map string column in Entity Framework to Enum

前端 未结 8 1163
被撕碎了的回忆
被撕碎了的回忆 2021-02-18 13:46

Is there a way to map a string column to an enum in an Entity Model?

I have done this in Hibernate, but can\'t figure it out in EMF.

相关标签:
8条回答
  • 2021-02-18 14:31

    I had the same problem. I've come up with a solution, but I'm not completely happy with it.

    My Person class has a Gender enum, and I use data annotations to map the string to the database and ignore the enum.

    public class Person
    {
        public int PersonID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    
        [Column("Gender")]
        public string GenderString
        {
            get { return Gender.ToString(); }
            private set { Gender = EnumExtensions.ParseEnum<Gender>(value); }
        }
    
        [NotMapped]
        public Gender Gender { get; set; }
    }
    

    here is the extension method to get the correct enum from the string.

    public class EnumExtensions
    {
        public static T ParseEnum<T>(string value)
        {
            return (T)Enum.Parse(typeof(T), value, true);
        }
    }
    

    I wrote a blog post about this - http://nodogmablog.bryanhogan.net/2014/11/saving-enums-as-strings-with-entity-framework/

    0 讨论(0)
  • 2021-02-18 14:34

    You can do either:

    Decorate the Enum property in your class as a text column

    [Column(TypeName = "nvarchar(50)")]
    public FileTypes FileType { get; set; }
    

    OR

    in your DatabaseContext class, override the OnModelCreating and add:

    modelBuilder
      .Entity<File>()
      .Property(e => e.FileType)
      .HasConversion(new EnumToStringConverter<FileTypes>());
    
    0 讨论(0)
提交回复
热议问题