2014-03-13 58 views
2

在为现有应用程序编写代码时,开发数据库环境通常与生产环境不匹配 - 甚至更糟糕的是,有些时候环境重叠并不是一种选择。Enum绑定到数据库

我想要为所有环境编码的一个想法是使用数据绑定枚举,其值将绑定到它们所代表的数据项的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在这个例子中得到红色的ID,无论我是否在开发,测试或生产的是的。

我的问题是:这真的是完成这个的理想方法吗?有没有一种数据绑定枚举的本地到C#的方法,或者等价于我在上面做的事情?

回答

0

拥有一个枚举意味着这些值很少会改变。你可以把它看作一个封闭的值列表(如一周中的某一天等)。由于枚举的这种性质,我发现可以接受这种冗余的枚举基础值被指定两次(一次在DB中,另一次在枚举本身中)。

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

+0

这对于期望更加恒定的值的枚举是有意义的。不过,对于差异验证 - 看起来像整体,这将是更多的手动过程来纠正每个环境的枚举。这听起来像枚举不是解决这类问题的方法 - 但是,我仍然想知道是否最好使用抽象类。 – Siyual