Enum与数据库绑定

本文关键字:绑定 数据库 Enum | 更新日期: 2023-09-27 17:49:45

在为现有应用程序编写代码时,开发数据库环境常常与生产环境不匹配——甚至更糟的是,有时仍然无法覆盖环境。

对于所有环境的编码,我想到的一个想法是使用一个绑定枚举,其值将绑定到它们所表示的数据项的ID。我不能让它与Enum一起工作,但我能够通过抽象类来解决它。例如:

public abstract class Colors
{
    private static readonly string c_red    = "red";
    private static readonly string c_blue   = "blue";
    private static readonly string c_yellow = "yellow";
    private static readonly string c_green  = "green";
    private static int? _red    = null;
    private static int? _blue   = null;
    private static int? _yellow = null;
    private static int? _green  = null;
    public static int Red
    {
        get
        {
            if (_red == null)
                _red = GetColorID(c_red);
            return (int)_red;
        }
    }
    public static int Blue
    {
        get
        {
            if (_blue == null)
                _blue = GetColorID(c_blue);
            return (int)_blue;
        }
    }
    public static int Yellow
    {
        get
        {
            if (_yellow == null)
                _yellow = GetColorID(c_yellow);
            return (int)_yellow;
        }
    }
    public static int Green
    {
        get
        {
            if (_green == null)
                _green = GetColorID(c_green);
            return (int)_green;
        }
    }
    private static int GetColorID(string identifier)
    {
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Demo"].ConnectionString))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("spGetColorId", conn))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("Name", identifier);
                return Convert.ToInt32(cmd.ExecuteScalar());
            }
        }
    }
}

通过这种方式,我可以在这个例子中调用Colors.Red来获得Red的ID,无论我是在Dev, Testing还是Production中。

我的问题是:这真的是实现这一目标的理想方法吗?是否有一种原生到c#的方法来绑定枚举,或者类似于我上面所做的?

Enum与数据库绑定

使用enum意味着这些值很少(如果有的话)被更改。你可以把它想象成一个封闭的值列表(比如星期几等)。

由于枚举的这种性质,我发现让枚举的基础值被指定两次(一次在数据库中,另一次在枚举本身中)的这种冗余是可以接受的。

如果您担心差异,您可以在应用程序启动时对值运行验证,并检查值是否具有正确的相应id,以及枚举中的值的数量是否与DB中的值的数量匹配。