You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I use custom converter for convert from enum to string and back (storing enum in DB as string)
publicclassCustomEnumConverter<TEnum>:ValueConverter<TEnum,string>whereTEnum:struct,Enum{publicCustomEnumConverter(ConverterMappingHintsmappingHints=null):base(toStringExpr, toEnumExpr, mappingHints){}privatereadonlystaticExpression<Func<TEnum,string>>toStringExpr=x => ToDbString(x);privatereadonlystaticExpression<Func<string,TEnum>>toEnumExpr=x => ToEnum(x);publicstaticstringToDbString(TEnumtEnum){varenumType= tEnum.GetType();varmemInfo= enumType.GetMember(tEnum.ToString());varattr=(EnumMemberAttribute)memInfo[0].GetCustomAttributes(typeof(EnumMemberAttribute),false).FirstOrDefault();return attr.Value;}publicstatic TEnum ToEnum(stringvalue){foreach(var name in Enum.GetNames<TEnum>()){varattr=typeof(TEnum).GetRuntimeField(name).GetCustomAttribute<EnumMemberAttribute>(true);if(attr!=null&& attr.Value ==value){return Enum.Parse<TEnum>(name);}}returndefault;}}
When I use standard EFCore functions (such as context.Sess.Add(entity)), all works fine (enums stored as string),
but batchUpdate save to DB int value of enum member, not string.
db.BatchUpdate<Entities.Sess>().Set(m => m.Status,m => Enums.SessStatus.Stopreq)// '1' in DB, must be 'stopreq'.Execute()
My Enum and Entity
public enum SessStatus
{
[EnumMember(Value = "active")]
Active,
[EnumMember(Value = "stopreq")]
Stopreq,
[EnumMember(Value = "stopping")]
Stopping,
}
public class Sess
{
...
public SessStatus Status { get; set; }
...
}
public class AppDbContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.Entity<Sess>()
.Property(m => m.Status)
.HasConversion(new Converters.CustomEnumConverter<SessStatus>());
base.OnModelCreating(modelBuilder);
}
}
The text was updated successfully, but these errors were encountered:
I use custom converter for convert from enum to string and back (storing enum in DB as string)
When I use standard EFCore functions (such as context.Sess.Add(entity)), all works fine (enums stored as string),
but batchUpdate save to DB int value of enum member, not string.
My Enum and Entity
The text was updated successfully, but these errors were encountered: