c# - 将 Entity Framework 中的字符串列映射到枚举

标签 c# .net database entity-framework orm

有没有办法将字符串列映射到实体模型中的枚举?

我已在 Hibernate 中完成此操作,但无法在 EMF 中解决。

最佳答案

可能是更好的版本。

OrderStateIdentifier 字段用于 JSON 序列化和数据库字段, 而 OrderState 只是为了方便在代码中使用。

    public string OrderStateIdentifier
    {
        get { return OrderState.ToString(); }
        set { OrderState = value.ToEnum<OrderState>(); }
    }

    [NotMapped]
    [JsonIgnore]
    public OrderState OrderState { get; set; }


public static class EnumHelper
{
    /// <summary>
    /// Converts string to enum value (opposite to Enum.ToString()).
    /// </summary>
    /// <typeparam name="T">Type of the enum to convert the string into.</typeparam>
    /// <param name="s">string to convert to enum value.</param>
    public static T ToEnum<T>(this string s) where T: struct
    {
        T newValue;
        return Enum.TryParse(s, out newValue) ? newValue : default(T);
    }
}

关于c# - 将 Entity Framework 中的字符串列映射到枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7437952/

相关文章:

c# - 在 C# 中,为什么 String 是一种行为类似于值类型的引用类型?

C# NamedValueCollection ToString 替换空格

c# - WP8 KnownContactProperties.Birthdate 无法设置值

.net - Interlocked.Xxx 方法是否保证在所有数据缓存中更新值?

mysql - mysql中如何分组、排序和取出前N个?

mysql - 在数据库中存储主题标签和用途/组合的最佳方式

c# - 多线程问题 - 线程完成后需要事件

c# - 更改 OWIN .expiration 和 .issued 日期的 DateTime 格式

C# Linq 对字典列表进行过滤

java - 如何在单个 Java 文件中维护多个 SQL 数据库连接?