通用列表<type>到枚举</type>

时间:2013-11-27 13:16:40

标签: c# list enums

我有以下课程

public partial class ActionType
{
    public System.Guid ActionTypeId { get; set; }
    public string ActionTypeName { get; set; }
}

现在我想使用存储在数据库中的所有ActionTypes:

MyEntity entity = new MyEntity();
entity.ActionTypeId = ActionTypes.??? 

这里我希望能够通过ActionTypeName选择ActionTypeId。

现在我这样做:

public class ActionTypes
{
    public static readonly Guid CustomerAdded = new Guid("36520b53-e1d0-4c96-bec8-0df85536a96b");
    public static readonly Guid CustomerEdited = new Guid("732592d3-7423-4250-aa74-e10fe1e7c030");
}

我希望能够从数据库中创建ActionTypes,而不是自己编写值。

所以我想做点什么:

public class ActionTypes
{
   List<ActionType> list = context.GetAllActionTypes();
   foreach(ActionType type in list)
   {
      public static readony Guid type.ActionTypeName = type.ActionTypeId;
   }
}

我如何实现我想要的目标?

最好的问候

2 个答案:

答案 0 :(得分:0)

也许您需要一个词典(查找表,地图)?

public class ActionTypes
{
   private List<ActionType> list = context.GetAllActionTypes();
   private Dictionary<string, Guid> ActionTypesMap { get; private set; }

   public ActionTypes() {
     this.ActionTypesMap = list.ToDictionary(
       k => k.ActionTypeName,
       v => v.ActionTypeId);
   }
}

访问:Guid addedGuid = new ActionTypes().ActionTypesMap ["CustomerAdded "]

答案 1 :(得分:0)

您可以使用T4模板在编译时生成文件。这具有保持智能感知和成员名称验证的额外好处。

这样的事情:

ActionTypes.tt:

<#@ template   language    = "C#"                           #>
<#@ assembly   name        = "Microsoft.CSharp"             #>
<#@ assembly   name        = "System.Core"                  #>
<#@ assembly   name        = "System.Data"                  #>
<#@ import     namespace   = "System.Collections.Generic"   #>
<#@ import     namespace   = "System.Dynamic"               #>
<#@ import     namespace   = "System.Linq"                  #>
<#@ import     namespace   = "System.Data.SqlClient"        #>

public class ActionTypes 
{
<#
var con = new SqlConnection("Data Source=localhost\SQLExpress;Initial Catalog=MyDatabaseName;Integrated Security=True");
con.Open();

var sqc = new SqlCommand("SELECT ActionTypeID, ActionTypeName FROM ActionTypes", con);
var reader = sqc.ExecuteReader();

using (var reader = sqc.ExecuteReader())
{
    while (reader.Read())
    {
#>
    public static Guid <#=reader.GetString(reader.GetOrdinal("ActionTypeName"))#> = new Guid("<#=reader.GetGuid(reader.GetOrdinal("ActionTypeID"))#>");
<#
    }
}
con.Close();
#>
}