将枚举与数据库的整数值返回值进行比较是最简单的方法 [英] What's the simplest way to compare an enum to a integer value return from a DB

查看:290
本文介绍了将枚举与数据库的整数值返回值进行比较是最简单的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用LINQ 2 SQL从表中提取一些数据...其中一个数据是一个值,表示我的应用程序代码中的一个枚举。



在LINQ对象返回的数据和应用程序代码中的枚举之间进行比较最简单的方法是什么。所以例如

 枚举SomeEnum 
{
首先
第二
}

然后在方法我有

 表< LinqObject> objects = dc.GetTable< LinqObject>(); 

foreach(对象中的var项目)
{
//做这个比较的最简单的方法是什么?
if(item.SomeNullableInteger == SomeEnum.First)//注意我意识到这不行!
{
//做某事...
}
}

我可以这样做

  SomeEnum.First.Equals(item.SomeNullableInteger)

或者我可以将枚举名称存储在数据库中,然后我可以这样做

  Enum.GetName(SomeEnum,SomeEnum.First)== item.SomeNullableName 

有更好的方法吗?枚举只有两个项目,它们很固定,可能有三分之一或四分之一,但可能永远不会超过这个。所以有一张整张桌子似乎是过度的。



其实这是一个重复的 C#int到枚举转换

解决方案

到基地类型。

  item.SomeNullableInteger ==(Int32)SomeEnum.First 

更新



最好最干净的解决方案可能是更新您的DBML文件。


  1. 在设计器中打开DBML文件。

  2. 选择枚举类型

  3. 打开属性窗口。

  4. 更改字段键入所选属性从 System.Int32 到类似于 global :: SomeNamespace.SomeEnum 的内容。也许它没有全球限定词,但我不确定。

现在,如果重新生成代码,属性将是枚举类型而不是整数。如果您具有可空属性,则当然必须使用可空的枚举类型。


I'm pulling some data from a table using LINQ 2 SQL...one of the pieces of data is a value that represents an enumation in my application code.

What is the simplest way to make a comparison between the data returned in LINQ objects and the enumeration in the application code. So for example

enum SomeEnum
{
  First
  Second
}

then in the method I have

Table<LinqObject> objects = dc.GetTable<LinqObject>();

foreach (var item in objects)
{
   // What's the simplest way to do this comparison???
   if (item.SomeNullableInteger == SomeEnum.First) // Note I realise this doesn't work!!!
   {
      // Do something...
   }
}

I could do this

SomeEnum.First.Equals(item.SomeNullableInteger)

or I could store the enumeration names in the database and then i'd be able to do this

Enum.GetName(SomeEnum, SomeEnum.First) == item.SomeNullableName

is there a better way? The enum only has two items and they're pretty fixed...could maybe have a third or a fourth but will probably never grow beyond that. So having a whole table seems like overkill.

Actually this is a duplicate of C# int to enum conversion

解决方案

This should work as expected - just cast to the base type.

item.SomeNullableInteger == (Int32)SomeEnum.First

UPDATE

The best and cleanest solution is probably to update your DBML file.

  1. Open the DBML file in the designer.
  2. Select the enumeration type property of the entity.
  3. Open the properties window.
  4. Change the field Type of the selected property from System.Int32 to something like global::SomeNamespace.SomeEnum. Maybe it will work without the global qualifier, but I am not sure.

Now, if the code is regenerated, the property will be of the enumeration type instead of a integer. If you have nullable properties, you must of course use a nullable enumeration type.

这篇关于将枚举与数据库的整数值返回值进行比较是最简单的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆