0

I have the following query which works fine

   var aaa = from d in _context.SubCategories
            join x in _context.CategoryLinks on d.ID equals x.SubCategoryID
            where x.CategoryID == CategoryID
            select new
            {
                 d.ID,
                 d.Name,
                 d.Code
            };

Now I'd like to convert it to linq method syntax, as imo it looks cleaner and instead of 'select new' I want to project it to the DM.SubCategory model.

How could I achieve this? I tried the code below but after typing cl.X it doesn't allow me to select any column enter image description here The CategoryLink table is only to check if there is a link between a category and subcategory. (containing ID, CategoryID & SubCategoryID with corresponding FK's)

Solved after projecting to result, still don't know why visual studio refuses to suggest the cl.X though

_context.SubCategories
           .Join(_context.CategoryLinks,
              sc => sc.ID,
              cl => cl.SubCategoryID,
              (sc, cl) => new { SubCategory = sc, CategoryLinks = cl })
           .Select(x => x.SubCategory);
Rick
  • 109
  • 13
  • `cl` should be the same datatype as an element in `_context.CategoryLinks`. If you hover over `cl` does it show that, or does it show as `Object`? – gunr2171 Mar 30 '20 at 14:20
  • No it shows as a DM.CategoryLink object. https://i.imgur.com/f3bdpV4.png – Rick Mar 30 '20 at 14:26
  • 1
    Uh....strange. If you just manually type out the name of the property, does it compile, even if autocomplete didn't suggest it? – gunr2171 Mar 30 '20 at 14:27
  • I tried that, as I assumed visual studio maybe needed a restart or some but then it gave me this error. i.imgur.com/5XB67Hs.png Got it working after projecting the result – Rick Apr 01 '20 at 11:24
  • If there's one aspect of LINQ that looks far uglier in method syntax than query syntax, it's joins – Caius Jard Apr 01 '20 at 11:26
  • I think it may simply be because you have code after the cursor insertion point (where your cursor currently is, with a following `)` you've only got 3 parameters in your join and it needs 4). Delete things so that all you've got is `_context.SubCategories .Join(_context.CategoryLinks, sc => sc.ID, cl => cl.` with nothing to the right of it, and try intellisense again? – Caius Jard Apr 01 '20 at 11:30

0 Answers0