If you’re using Entity Framework with a legacy database then you may well have single character status flags in some of the columns such as “O” = Operational, “M” = Marketing.

Ideally these would be numeric IDs that match to a separate status table which would allow the IDs to be set to the enum ID in your entity model for smooth conversion. However if that’s not the case you can set the enum ID to be the char value of the field and then use the Entity Framework conversion methods to specify how the field should be converted to and from the enum value in your object model.

In my case I was reading rows from a SQL database and inserting them into a table in Azure Table Storage, by default Table Storage stores enums as integer values but it’s possible to convert these values to strings as I’ve previously posted about.

public class ProductEntity : TableEntity
{
	public ProductEntity()
	{
	}

	public ProductEntity(string productId, string sequenceId)
	{
		this.PartitionKey = productId;
		this.RowKey = sequenceId;
	}

	public int Hierarchy { get; set; }

	public string ImageUrl { get; set; }

	public string TargetUrl { get; set; }

	[EntityEnumPropertyConverter]
	public MessageType MessageType { get; set; }
	
	public override IDictionary<string, EntityProperty> WriteEntity(OperationContext operationContext)
	{
		var results = base.WriteEntity(operationContext);
		EntityEnumPropertyConverter.Serialize(this, results);
		return results;
	}

	public override void ReadEntity(IDictionary<string, EntityProperty> properties, OperationContext operationContext)
	{
		base.ReadEntity(properties, operationContext);
		EntityEnumPropertyConverter.Deserialize(this, properties);
	}
}
public class ProductContext : DbContext
{
	private readonly string _dataConnectionString;

	public DbSet<ProductEntity> Products { get; set; }

	public ProductContext(string dataConnectionString)
	{
		_dataConnectionString = dataConnectionString;
	}

	protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
	{
		optionsBuilder.UseSqlServer(_dataConnectionString);
	}

	protected override void OnModelCreating(ModelBuilder modelBuilder)
	{
		modelBuilder.Entity<ProductEntity>()
			.Property(p => p.MessageType)
			.HasConversion<char>(p => (char)p, p => (MessageType)(int)p);
	}
}

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *