2013-04-23 77 views
2

因此,我试图使用枚举,可能以错误的方式,因为我来自PHP。在C#中我有一个全球性的类,它的作用:了解枚举 - 用作常量

public static class GlobalTypes 
{ 
    public enum assignmentType { SERV = "SERV", PROD = "PROD", PER = "PER", } 
} 

从那里我试图与实体交互做:

public static IEnumerable<Person> getAllAgents(int id) 
    { 
     using (var db = new LocAppContext()) 
     { 
      var person = (from p in db.Person 
          join la in db.LocationAssignment on p.id equals la.value 
          where la.locationID == id && la.type == GlobalTypes.assignmentType.PER 
          select p).ToList(); 

      return person; 
     } 

    } 

但我得到的错误:

Operator '==' cannot be applied to operands of type 'string' and 'LocApp.Helpers.Classes.LocationAssignments.GlobalTypes.assignmentType'

发生在

la.type == GlobalTypes.assignmentType.PER 

我的逻辑,这是从PHP的,是我想要一个全局常量,我可以调用任何地方“回声”调用时,该常量的值,所以恒定值可以改变,但我不必改变它在一百万个地方。

想法?

+1

只需沟'= “SERV”'部分,它应该是好的去。下面是关于C#中枚举用法的一些MSDN文档:http://msdn.microsoft.com/en-ca/library/vstudio/cc138362.aspx编辑:另外,你的'la.type'应该被定义为'GlobalTypes.assignmentType '不是一个字符串。 – 2013-04-23 20:20:48

+6

枚举不是字符串,C#不是PHP。 – alex 2013-04-23 20:21:30

+0

@ChrisSinclair所以你说我可以这样做:'&& GlobalTypes.assignmentType' ??它会知道我想要什么? – TheWebs 2013-04-23 20:23:05

回答

4

如果你想要不变的字符串,那就不要使用枚举。枚举是用于整数类型。只需使用consts:

public static class MyClass 
{ 
    public const string PROD = "PROD"; 
    public const string DEV = "DEV"; 
} 

// elsewhere... 
la.type == MyClass.PROD; 
4

快速回答:

public enum assignmentType { SERV, PROD, PER } 

,并在比较中(假设la.type返回一个字符串):

where la.locationID == id && la.type == GlobalTypes.assignmentType.PER.ToString() 
+3

即使你不必使用枚举,你为什么不想这么做呢?使用枚举听起来像是解决这个问题的完美解决方案。 – Servy 2013-04-23 20:30:49

+0

问题:LINQ to Entities无法识别方法'System.String ToString()'方法,并且此方法无法转换为存储表达式。 la.type,befor这是:la.type ==“PER”所以是它的一个字符串,错误仍然存​​在 – TheWebs 2013-04-23 20:34:43

+1

同意@Servy。枚举是一个很好的解决方案,因为它被用来对3个值进行分组。使用常量作为别人建议删除分组。也许使用ToString并保存到查询中使用的临时字符串。枚举在代码中的其他位置重用是有意义的。 – Dave 2013-04-23 20:37:16