How to save enum in database as string

后端 未结 6 697
北恋
北恋 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:48

    Explicit enum to string conversions would make your code messy and you'd have to keep parsing values. The same goes for lookup tables. Just add [Column] attribute to your enum field and specify TypeName as nvarchar (for SQL) or varchar (for postgres). Worked for me like a charm. In your case, for example :

    public class User
    {
        public int ID { get; set; }
    
        public string Name { get; set; }
    
        [Column(TypeName = "nvarchar(20)")]
        public Type Type { get; set; }
    
        public List WeposInList { get; set; }
    
        }  
    

    You can read more about it in the official documentation here

提交回复
热议问题