简体   繁体   中英

LINQ 'query syntax' — where clause filtering against List of int

Struggling on how to get this filter to work:

  var categoryIDs = new List<int>();
              categoryIDs.Add(2);
              categoryIDs.Add(3);

             var dbContacts = (from cnt in _db.Contacts
                join ucc in _db.UserContactCategories on cnt.id equals ucc.ContactID
                join cat in _db.Categories on ucc.CatDescID equals cat.id
                where categoryIDs.Equals(cnt.id)
                select new {cnt.id,
                    cnt.GivenName,
                    cnt.SurName                         
                }).ToList(); 

Getting this error message:

Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types

You are are trying to compare a List<int> to an int , which won't work.

If you're looking to get all contacts that are in your hard coded List<int> , just use the Contains method.

var categoryIDs = new List<int>();
              categoryIDs.Add(2);
              categoryIDs.Add(3);

             var dbContacts = (from cnt in _db.Contacts
                join ucc in _db.UserContactCategories on cnt.id equals ucc.ContactID
                join cat in _db.Categories on ucc.CatDescID equals cat.id
                where categoryIDs.Contains(cat.id)
                select new {cnt.id,
                    cnt.GivenName,
                    cnt.SurName                         
                }).ToList(); 

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