C# 如何使用db int来存储启用了特定enum标志的对象
我有一个带有标志enum的对象,它有几个可能的“用法”。标志枚举使用2的适当幂 检查某个变量是否启用了某个标志,我可以使用.NET 4C# 如何使用db int来存储启用了特定enum标志的对象,c#,.net-4.0,entity-framework-4.1,C#,.net 4.0,Entity Framework 4.1,我有一个带有标志enum的对象,它有几个可能的“用法”。标志枚举使用2的适当幂 检查某个变量是否启用了某个标志,我可以使用.NET 4HasFlag() 但是: 如果我在数据库中将该标志组合存储为int。。。如何使用实体框架检索具有特定标志的对象 例如,如果我的对象是“Contact”类型,我想查询那些实际上是“客户和朋友”的对象,它们是ContactTypeEnum中的客户和朋友标志。我怀疑任何ORM都不会有办法将HasFlags向下调整为适合您DBMS的SQL代码 您可能需要做的是编写一个存
HasFlag()
但是:
如果我在数据库中将该标志组合存储为int。。。如何使用实体框架检索具有特定标志的对象
例如,如果我的对象是“
Contact
”类型,我想查询那些实际上是“客户和朋友”的对象,它们是ContactType
Enum中的客户和朋友标志。我怀疑任何ORM都不会有办法将HasFlags向下调整为适合您DBMS的SQL代码
您可能需要做的是编写一个存储过程,或者手动启动要为此执行的SQL语句
您没有提到您使用的是什么DBMS,但是如果我假设您使用的是SQL Server,那么您就很幸运了,因为它具有相同的功能
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
您可以将组合的位值获取为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;
现在可以继续并将该值存储在db中。如果要查询多个位标志,请执行以下操作:
- 把它们结合起来
- 将它们转换为int
- 并在
子句中将结果变量/值用作过滤器Where
// 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;