简体   繁体   中英

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 . 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 . 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.

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 .

Database.EmailSettings.FirstOrDefault(
    es => es.EmailType.HasFlag(EmailType.PasswordRecovery));

I think EmailType == 3 is one of your conditions? Maybe you can get the results using other conditions first, and then filter with this condition in C# code using Enum.HasFlag method. If this is the only condition you want to query, maybe you can store "1,2" instead of "3" in DB.

I was looking for the solution of filtering data using multiple enum values but I was not getting any good solution. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM