在数据库中保存枚举列表



我有List<object>枚举列表,这是我编写的一些模式匹配代码的结果。

我的问题是我想在数据库中保存这个枚举列表,以便将来可以再次应用此模式,但我有点困惑如何做到这一点。

枚举列表包含不同的枚举,例如:

EnumType1.SomeVaue
EnumType2.SomeValue

我也不知道有多少枚举,也不知道它们的顺序。我正在努力想出一个好方法来序列化这个数据库,这样List<object>列表可以在以后用相同的枚举重新创建,以反馈到我的代码。

我想知道是否用枚举表示模式段是一个坏主意,我应该回去重构所有的代码?

可以将枚举转换为包含枚举类型的字符串,然后再转换回来吗?

可以将不同的enum int值保存到数据库中。例如

public enum Animal {Dog = 0, Cat = 1, Bird = 2}
public class Person
{
    public Animal Pet {get; private set;}
    public Person()
    {
        Pet = Animal.Dog;
    }
    public void Insert()
    {
        using(var con = DbFactory.CreateConnection(Database))
        {
            con.Query("stored_procedure_here", new { Pet = this.Pet}, CommandType.StoredProcedure);
        }
    }

}

在您的数据库中,您将有一个Pet作为整数的表。保存Dog的整数值0。然后,当你拉出枚举的值(0),枚举将自动知道它是狗。我希望这是有意义的……关于stackoverflow的整个回答都是新的:))

编辑:

好吧,如果列表中有多种类型的枚举,你可以有一个保存int值的表和另一个包含枚举的类型/名称的列。当你把它拉出来的时候,你可以有某种逻辑把它组织到适当的枚举中。我猜. .

 //Get the Name/Type and the int from the database for example Dog, 0
 string enumName = "Dog";
 int enumValue = 0
 Type enumType = Type.GetType(enumName);
 if (enumType == null)
 {
     throw new ArgumentException("Specified enum type could not be     found", "enumName");
 }
 object value = Enum.Parse(enumType, enumValue);

}

最新更新