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