-1

我有一张桌子叫DynamicControl. 它有一个名为 的属性ControlTypenvarchar(255)位于 SQL Server 2008 数据库中。

在代码中,我希望属性值是一个字符串,但它的字符串值必须来自枚举的字符串表示形式,如下所示:

public enum ControlType
{
    TextBox,
    TextArea,
    Password,
    RadioButton,
    Checkbox,
    DropDownList,
    MultiSelectList,
    DatePicker,
    TimePicker,
    DateTimePicker
}

我怎么做?

更新 我忘了添加一些重要的信息,但没有提供,这听起来像是一个愚蠢的问题。问题是:我没有使用 POCO。我受限于使用实体框架生成的模型类。如果我正在编写 POCO,我只需将数据类型更改为枚举。但是,由于我使用的是生成的模型,这样做会导致 EDMX 标记和模型类之间存在差异。

更新我的问题是,我如何告诉实体框架在 EDMX 中生成正确的标记,以便所述属性的类型是 ControlType 枚举而不是字符串或 Int32?

因此,我的问题不是 如何将枚举转换为字符串,反之亦然

4

3 回答 3

0

只需将您的属性定义为您的枚举类型(即:ControlType)

于 2013-05-07T13:11:43.420 回答
0

.Net 框架中的枚举类有很多静态成员函数来帮助 ypu。假设您从 DB 获取 nvarchar 值到一个名为 dbCtrlType 的字符串变量中,那么

 public ControlType ControlTypeEnum
 {
     get { return (ControlType)Enum.Parse(typeof(ControlType), dbCtrlType); }
     set { dbCtrlType = dbCtrlType.ToString(); }
 }
于 2013-05-07T13:15:54.343 回答
0

If I got it correct then you need something similar with little fine-tuning

using System;
using System.ComponentModel;
namespace ConsoleApplication1
{
    public enum ControlDefaultClass
    {
        [Description("This is some string which you wanted to show")] MemberA,
        [Description("This is some other string which you wanted to show")] MemberB,
    }

    public class ConsoleApp
    {
        private static void Main(string[] args)
        {
            Console.WriteLine(GetDescription(ControlDefaultClass.MemberA));  //This line will print - This is some string which you wanted to show
            Console.WriteLine(GetDescription(ControlDefaultClass.MemberB));//This line will print - This is some other string which you wanted to show
            Console.Read();
        }

        public static string GetDescription(Enum value)
        {
            var fieldInfo = value.GetType().GetField(value.ToString());
            var attributes =
                (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);

            return attributes.Length > 0 ? attributes[0].Description : value.ToString();
        }
    }
}
于 2013-05-07T13:19:24.070 回答