0

I want to extract a list using linq as tree structure.

{
    "details": [
        {
            "description":"This is description 1",
            "Name": "Name 1"
        },
        {
            "description":"This is description 2",
            "Name": "Name 2"
        }
    ],
    "price": 100
}

I have one detailsDto as List<> in hand which i will use it in Details field

properties from 'm' instance will be bind in detailsDto. that's where i am facing problem on how to do it. description and name field available in 'm' instance

var data = await Task.FromResult((
    from c in _context.C
    join mc in _context.MC on c.VId equals mc.VId
    join m in _context.M on mc.Id equals m.mcId
    where mc.Id == mcId && c.Id == CId
    select new MainDto()
    {
        Price = mc.Price,
        // Details =
    }
    ).FirstOrDefault()
);
Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
  • Can you elaborate on how your code "doesn't work"? What were you expecting, and what actually happened? If you got an exception/error, post the line it occurred on and the exception/error details which can be done with a [mre]. Please [edit] your question to add these details into it or we may not be able to help. – gunr2171 Dec 29 '22 at 13:30
  • Can you include your dbcontext file? – Mocas Dec 29 '22 at 13:55
  • does that really need? @Mocas – Saleh Sayeem Dec 29 '22 at 14:07

2 Answers2

0

Probably you need this query:

var data = await (
    from c in _context.C
    join mc in _context.MC on c.VId equals mc.VId
    where mc.Id == mcId && c.Id == CId
    select new MainDto()
    {
        Price = mc.Price,
        Details = _context.M.Select(m => new DetailsDto 
        {
            Name = m.Name,
            description = m.Description,
        }).ToList()
    }
    ).FirstOrDefaultAsync();
Svyatoslav Danyliv
  • 21,911
  • 3
  • 16
  • 32
0

this should be helpful

{
    Price = mc.Price,
    Details = m.Select(x => new DetailDto
    {
        Description = x.Description,
        Name = x.Name
    }).ToList()
}

It will create a new instance of the DetailDto class for each element in the m list and assign the values of the Description and Name properties to the corresponding properties in the DetailDto instance.

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
  • that select keyword doesn't work.. and i can only access single property of 'm' . like, m.name, m.id etc. but i need a list – Saleh Sayeem Dec 30 '22 at 12:15