1

I am looking for a better way to structure my application so that I can work with enums using entity framework, and cases where I would need to use TSQL eg stored procs ,common table expressions etc.It looks great to use it on the linq to Entities side , but on the TSQL side it does not look that nice eg when projecting the results and you want the enum string values.I have already looked at the EF enum support tutorial here and other examples from the web and on SO and I just cant seem to find a standard way

Part of the code from the tutorial here

public enum DepartmentNames
{
  English,
  Math,
  Economics
}    

public partial class Department
{
  public int DepartmentID { get; set; }
  public DepartmentNames Name { get; set; }
  public decimal Budget { get; set; }
}

My list of questions are:

  • how to deal with enums in case of stored procs or common table expressions, or anything requiring TSQL, rather than linq to Entities
  • suppose I create a class for EF to store the enum values,is it best practice to have an equivalent table in my database for the enum, by creating an equivalent class like in the code below, and manualy adding the State1 ,State2 values in the EF seeding process etc.
  • following above ,what is the best way to name + structure the enum ,like you can see from the code

for example

public class SomeStateType
{
    public int SomeStateTypeId { get; set; }
    public string Name { get; set; }

    public enum Type
    {
        State1 = 1,
        State2 = 2,
    }
}
4

2 回答 2

1

在示例中,枚举的整数值存储在数据库中,而不是字符串。EF 将整数值映射到您的枚举值。就我个人而言,我更喜欢像您一样明确编号枚举的每个值,但不将枚举嵌套在 db 模型类中 - 原因可能是您可能希望能够在其他地方使用枚举来检查您的 db 对象的“状态” .

//Model
public class Course
{
    public int ID { get; set; }
    public CourseTypes CourseType { get; set; }
    //stuff omitted
}

public enum CourseTypes
{
    [Description("Training")]
    Training = 1,
    [Description("Awareness Only")]
    AwarenessOnly = 2
    //etc
}

而且我使用了一个辅助方法(我在 SO 上找到,但没有正确信用的链接,抱歉)来获取枚举的描述属性,以便我可以在需要时拥有一个可呈现的字符串,而不是 name 属性.

public static string GetEnumDescription<TEnum>(TEnum value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());

        DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

        if ((attributes != null) && (attributes.Length > 0))
            return attributes[0].Description;
        else
            return value.ToString();
    }
于 2013-10-29T13:14:21.800 回答
1

我的代码中有一些枚举。

一些事情:

  • 枚举不是字符串。上面的例子分别English, Math, Economics代表了数字0,1,2
  • 我检查了我的数据库,但找不到枚举,所以我猜 EF 没有为它们创建表(不过我可能错了)
  • 当你创建一个 Enum 时,类型就是你的 Enum,就像上面的例子一样。在您的情况下,它将是:public Type *name of your property*

祝你好运!

于 2013-10-29T12:56:11.523 回答