将枚举与数据库的整数值返回值进行比较是最简单的方法 [英] What's the simplest way to compare an enum to a integer value return from a DB
问题描述
在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文件。
- 在设计器中打开DBML文件。
- 选择枚举类型
- 打开属性窗口。
- 更改字段
键入
所选属性从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.
- Open the DBML file in the designer.
- Select the enumeration type property of the entity.
- Open the properties window.
- Change the field
Type
of the selected property fromSystem.Int32
to something likeglobal::SomeNamespace.SomeEnum
. Maybe it will work without theglobal
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屋!