How to save enum in database as string

后端 未结 6 684
北恋
北恋 2020-12-29 02:59

This is my Model Class where we have a Type which could be a Zombie or Human

public class User
{
    public int ID { get; set; }
    public string Name { ge         


        
6条回答
  •  攒了一身酷
    2020-12-29 03:27

    You can save the enum to the db as a string, and I agree with dotctor that it is not the best idea, but if you need to, you need to make a few changes.

    public class User
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public List WeposInList { get; set; }
    
        [Column("Type")]
        public string TypeString
        {
           get { return Type.ToString(); }
           private set { Type= value.ParseEnum(); }
        }
    
        [NotMapped]
        public Type Type { get; set; }
    }  
    

    Add this extension class to your project.

    public static class StringExtensions
    {
        public static T ParseEnum(this string value)
        {
            return (T)Enum.Parse(typeof(T), value, true);
        }
    }
    

    Full details are here - http://NoDogmaBlog.bryanhogan.net/2014/11/saving-enums-as-strings-with-entity-framework/

提交回复
热议问题