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#的方法,或者等價於我在上面做的事情?
這對於期望更加恆定的值的枚舉是有意義的。不過,對於差異驗證 - 看起來像整體,這將是更多的手動過程來糾正每個環境的枚舉。這聽起來像枚舉不是解決這類問題的方法 - 但是,我仍然想知道是否最好使用抽象類。 – Siyual