How to use flags enums in Linq to Entities queries?

后端 未结 8 1012
轮回少年
轮回少年 2021-01-01 04:33

I have a [Flags] enum like this:

[Flags]
public enum Status
{
  None = 0,
  Active = 1,
  Inactive = 2,
  Unknown = 4
}

A Status enum may c

相关标签:
8条回答
  • 2021-01-01 05:01

    I don't know EF, but could inserting additional casts work?

    var result = from r in db.Records
                 where ((byte)r.Status & (byte)s) == (byte)r.Status
                 select r
    
    0 讨论(0)
  • 2021-01-01 05:02

    Take a look at the following good post, it shows you the following alternatives:

    • At least one of the selected flags set
    • Exactly the same flags set
    • At least those flags you selected and more

    https://timdams.wordpress.com/2011/02/14/using-enum-flags-to-write-filters-in-linq/#comment-30

    0 讨论(0)
  • 2021-01-01 05:09

    Just use HasFlag()

    var result = from r in db.Records
             where r.Status.HasFlag(s)
             select r
    
    0 讨论(0)
  • 2021-01-01 05:10

    The folloiwng works for me in C#

        public const StatusTypes ActiveAlert = StatusTypes.Accepted | StatusTypes.Delivered;
    
            int flags = (int)ActiveAlert;
    
            try
            {
                var query = from p in model.AlertsHistory
                            where (p.UserId == clientId
                            && (p.Status.HasValue && (p.Status.Value & flags) != 0))
                            select p;
                var aList = query.ToList();
    
                return (aList);
    
    
            }
            catch (Exception exc)
            {
                log.Error("Exception getting Alerts History for user.", exc);
                throw;
            }
    
    0 讨论(0)
  • 2021-01-01 05:11

    In DB Flags enum must be integer. After that you can try it like this:

    Status s = Status.Active | Status.Unknown;
    
    var result = from r in db.Records
    where (s & r.Status) == r.Status
    select r
    
    0 讨论(0)
  • 2021-01-01 05:19

    Try it like this:

    byte status = (byte)(Status.Active | Status.Unknown);
    
    var result = from r in db.Records
                 select r
                 where (r.Status & status) != 0
    
    0 讨论(0)
提交回复
热议问题