如何查询具有特定枚举标志的对象,使用db-int存储它

本文关键字:对象 标志 使用 存储 db-int 枚举 何查询 查询 | 更新日期: 2023-09-27 18:28:03

我有一个带有Flag枚举的对象,该对象有几种可能的"用途"。标志枚举使用2的适当幂。

检查变量是否有特定的标志,我可以使用.NET 4 HasFlag() 进行检查

但是:

如果我将该标志组合作为int存储在数据库中。。。如何在使用实体框架时检索具有特定标志的对象?

例如,如果我的对象是"Contact"类型,我想查询其中实际上是"客户和朋友"的对象,即ContactType枚举中的客户和朋友标志。

如何查询具有特定枚举标志的对象,使用db-int存储它

我怀疑任何ORM都无法将HasFlags调整为适用于DBMS的适当SQL代码。

您可能需要做的是编写一个存储过程,或者手动编写要为此执行的SQL语句。

您没有提到您正在使用的DBMS,但如果我假设您正在使用SQL Server,那么您很幸运,因为它具有&(按位AND)运算符。

T-SQL:的实际示例

-- Setup Test Data 
DECLARE @Contacts TABLE (id int, contactType int, name nvarchar(MAX)) 
INSERT INTO @Contacts VALUES (1, 0, 'Fred'); -- Not Wanted
INSERT INTO @Contacts VALUES (2, 3, 'Jim');  -- Wanted
INSERT INTO @Contacts VALUES (3, 36, 'Mary');  -- Not wanted
INSERT INTO @Contacts VALUEs (4, 78, 'Jo');  -- Wanted
-- Execute Query
SELECT *
FROM @Contacts
WHERE ContactType & 2 = 2 
db.Contacts.Where(c => (c.Flag & MyEnum.Flag3) != 0).ToList();

您可以将组合的位值作为int,并将该值作为列存储在db中。以下是一个示例:

public enum MessagingProperties
{
    // No options selected (value is 0)
    None = 0x00,
    // messages are not discarded if subscriber is slow (value is 1)
    Durable = 0x01,
    // messages are saved to disk in case messaging crashes (value is 2)
    Persistent = 0x02,
    // messages are buffered at send/receive point so not blocking (value is 4)
    Buffered = 0x04
}

为了组合这些标志枚举,您需要:

// combine the bit flags
var combinedFlags = MessagingProperties.Durable | MessagingProperties.Persistent | 
                     MessagingProperties.Buffered;
// this will be equal 7, no other combination can sum up to seven so it is unique, that's how bit flags work
int combinedFlagsInt = (int)combinedFlags;

现在,您可以继续将此值存储在数据库中。如果你想查询多位标志,你:

  • 将它们合并
  • 将它们转换为int
  • 并将得到的变量/值用作CCD_ 4子句中的过滤器