[英]linq-To-Sql: filter with enum(flags)
I have a enum:我有一个枚举:
[Flags]
public enum EmailType
{
PasswordRecovery = 1,
Activation = 2,
SendTicket = 4
}
For example, in a table we have value equals 3 that means - PasswordRecovery
, Activation
.例如,在一个表中,我们的值等于 3,这意味着 - PasswordRecovery
、 Activation
。 This is my query:这是我的查询:
var emailType = EmailType.PasswordRecovery;
return Database.EmailSettings.FirstOrDefault(es => es.EmailType == (int)emailType);
Of course this query not works properly: 3 == 1 => false
.当然这个查询不能正常工作: 3 == 1 => false
。 How to filter properly?如何正确过滤?
Thanks.谢谢。
UPDATE: I'm using Flags
attribute because there is one more application written with XAF (devexpress framework) and I have one feature in UI that required Flags
attribute.更新:我正在使用Flags
属性,因为还有一个使用 XAF(devexpress 框架)编写的应用程序,并且我在 UI 中有一个需要Flags
属性的功能。
int emailType = (int)EmailType.PasswordRecovery;
return Database.EmailSettings.FirstOrDefault(es => (es.EmailType & emailType) == emailType);
Edit: I added a cast since es.EmailType
is and int
. 编辑:我添加了一个演员,因为es.EmailType
是和int
。
Database.EmailSettings.FirstOrDefault(
es => es.EmailType.HasFlag(EmailType.PasswordRecovery));
I think EmailType == 3
is one of your conditions? 我认为EmailType == 3
是你的条件之一? Maybe you can get the results using other conditions first, and then filter with this condition in C# code using Enum.HasFlag method. 也许您可以先使用其他条件得到结果,然后使用Enum.HasFlag方法在C#代码中使用此条件进行过滤。 If this is the only condition you want to query, maybe you can store "1,2" instead of "3" in DB. 如果这是您要查询的唯一条件,也许您可以在DB中存储“1,2”而不是“3”。
I was looking for the solution of filtering data using multiple enum values
but I was not getting any good solution.我一直在寻找使用multiple enum values
过滤数据的解决方案,但我没有得到任何好的解决方案。 Then I explored it by the solution that I mentioned below:然后我通过下面提到的解决方案进行了探索:
Here is the enum:这是枚举:
[Flags]
public enum TransmissionType
{
None = 0,
Automatic = 1,
CVT = 2,
DCT = 4,
Manual = 8,
SemiAutomatic = 16,
SportAT = 32,
Unspecified = 64
}
Here is the code where we filter cars
list using multiple enum values
这是我们使用multiple enum values
过滤cars
列表的代码
if (input?.Filter?.Transmissions.Count() > 0)
{
var transmissionTypes = new List<TransmissionType>();
foreach (var item in input?.Filter?.Transmissions)
{
transmissionTypes.Add((TransmissionType)
Enum.Parse(typeof(TransmissionType), item, true));
}
cars = cars.Where(d => transmissionTypes.Contains(d.Transmission));
}
Here cars is the list of cars from dbContext and
input?.Filter?.Transmissions
contains multiple enum values as string array这里的汽车是来自 dbContext 和input?.Filter?.Transmissions
包含多个枚举值作为字符串数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.