将按位枚举映射到 sql 列值 [英] Map bitwise enum to sql column value

查看:38
本文介绍了将按位枚举映射到 sql 列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个按位枚举,FlagsAttribute 像这样设置 -

I have a bitwise enum with FlagsAttribute set over it like this -

[FlagsAttribute]
public enum MyEnum
{
    None = 0,
    First = 1,
    Second = 2,
    Third = 4,
    Five = 8,
    Six = 16,
    Seven = 32,
    Eight = 64,
    Nine = 128
}

现在,在 C# 中,我将此值存储在一个属性中,例如 MyProperty,并在保存时将此属性写入我的 SQL 数据库的整数列中.假设如果我从代码中选择 First,Second,Five 那么在数据库中它将被保存为 '11'.

Now, in C# i am storing this value in a property say MyProperty and on save i write this property in my SQL database in integer column. Suppose if i select First,Second,Five from code then in database it will be saved as '11'.

我知道我可以从数据库中获取值,只需要将 int 值类型转换为 MyEnum,它就会给我这些值.但是,我希望在某些存储过程中对 SQL 数据进行一些操作,显然我无法将其类型转换为 Enum 值.那么,有没有办法让我知道个人价值.

I know i can fetch value from DB and just need to typecast int value to MyEnum and it will give me the values. But, i want some manipulation to be done on SQL data in some Stored procedure where obviously i can't typecast it to Enum value. So, is there a way out which can let me know about the individual values.

例如,如果存储了 11,我可以通过任何方式将其作为 "1+2+8"

Like in example if 11 is stored, any way that i can get it as "1+2+8"

推荐答案

这可能有助于您入门:

Select 11 & 1 As 'First'
  , 11 & 2 As 'Second'
  , 11 & 4 As 'Third'
  , 11 & 8 As 'Five'
  , 11 & 16 As 'Six'
  , 11 & 32 As 'Seven'
  , 11 & 64 As 'Eight'
  , 11 & 128 As 'Nine';

其中 11 是您存储的价值.

Where 11 is your stored value.

这将为设置的每个值返回非零值(即 Select 11 & 1 As 'First' 返回 1, Select 11 &; 2 As 'Second' 返回 2,Select 11 & 4 As 'Third' 返回 0 以此类推.

This will return non-zero values for each value that is set (i.e. Select 11 & 1 As 'First' returns 1, Select 11 & 2 As 'Second' returns 2, Select 11 & 4 As 'Third' returns 0 and so on.

这篇关于将按位枚举映射到 sql 列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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