using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using System.Collections.Generic;
using System.Text.Json.Serialization;
public static void Main()
using (var _context = new TestContext())
_context.Database.EnsureCreated();
_context.Models.AddRange(new List<Model>
new Model { Type = ItemType.Wall },
new Model { Type = ItemType.Floor },
var _models = _context.Models.ToList();
Console.WriteLine(JsonSerializer.Serialize(_models,
new JsonSerializerOptions
new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)
public class TestContext : DbContext
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
.UseSqlServer(FiddleHelper.GetConnectionStringSqlServer(), o => o
.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery))
.UseSqlServer(FiddleHelper.GetConnectionStringSqlServer(), o => o
.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery))
protected override void OnModelCreating(ModelBuilder modelBuilder)
var enumDescriptionMappingConverter = new ValueConverter<ItemType, string>(
v => EnumExtensions.GetValueByDescriptionAttribute<ItemType>(v));
Console.WriteLine("ConvertFromProviderExpression: " + enumDescriptionMappingConverter.ConvertFromProviderExpression);
Console.WriteLine("ConvertToProviderExpression: " + enumDescriptionMappingConverter.ConvertToProviderExpression);
modelBuilder.Entity<Model>()
.HasConversion(enumDescriptionMappingConverter);
public DbSet<Model> Models { get; set; }
public static class EnumExtensions
public static string ToDescription(this Enum value)
var attribute = value.GetAttribute<DescriptionAttribute>();
return attribute.Description;
public static TEnum GetValueByDescriptionAttribute<TEnum>(string value)
var enumDict = Enum.GetValues(typeof(TEnum))
.ToDictionary(k => k, v => v.ToDescription());
.Single(x => x.Value == value)
private static T GetAttribute<T>(this Enum value)
Type type = value.GetType();
MemberInfo[] memberInfo = type.GetMember(value.ToString());
var attributes = memberInfo[0].GetCustomAttributes(typeof(T), false);
return (T)attributes.FirstOrDefault();
public int Id { get; set; }
public ItemType Type { get; set; }