简体   繁体   中英

Does not contain definition for 'Contains'

It is showing the error like "doesn't contain definition for ID" for the code

[HttpPost]
public ActionResult show(List<int> ids)
    {
        if (ids != null)
        {
            int[] brands = ids.ToArray();
            var brandId = _db.Brands.Where(p => brands.Contains(p.ID));
            var srtItems = _db.Products.Where(p => p.CategoryID == brandId.ID);

            return PartialView("_pView", srtItems);
        }
    }

and for the following code the error is' doesn't contain definition for Contains'

[HttpPost]
        public ActionResult show(List<int> ids)
        {
            if (ids != null)
            {
                int[] brands = ids.ToArray();
                var brandId = _db.Brands.Where(p => brands.Contains(p.ID));

                var sortItemss = _db.Products.Where(p => brandId.Contains(p.CategoryID));
                return PartialView("_pView", srtItems);
            }

Please guide me

This is where var becomes the root of all evil as it hides the real data type. Drop the var and you'll notice the problem immediately:

int[] brands = ids.ToArray();
IQueryable<Brand> brandId = _db.Brands.Where(p => brands.Contains(p.ID));
IQueryable<Product> srtItems = _db.Products.Where(p => p.CategoryID == brandId.ID);

brandId is a sequence (when materialized) and it is not a single object, so it doesn't contains a definition of ID .

To solve that, you can:

IQueryable<int> brandIds = _db.Brands.Where(p=> brands.Contains(p.ID)).Select(b=> b.ID);
IQueryable<Product> srtItems = _db.Products.Where(p=> brandIds.Contains( p.CategoryID));

Get the IDs of the retrieved records, and match by those IDs.

As an advice , don't use var unless the real type is redundant (meaning it shows in other parts of the statement)

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