Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Select All with a One to Many Relationship Using Linq

I have two tables:

CREATE TABLE Thing (
    Id int,
    Name nvarchar(max)
);

CREATE TABLE SubThing (
        Id int,
        Name nvarchar(max),
        ThingId int (foreign key)
    );

I want to select all Things with a listing of SubThings and set them to a ThingViewModel.

The Thing ViewModel is simple:

public class ThingViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<SubThingViewModel> SubThings { get; set; }
}

The SubThingViewModel is:

public class SubThingViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

I already select the Thing records like this:

List<ThingViewModel> things = null;
things = _context.Things.OrderBy(b => b.Name)
    .Select(b => new ThingViewModel
    {
         Id = b.Id,
         Name = b.Name
    }).ToList();

How would I add the SubThings to the query and ViewModel?

like image 743
crackedcornjimmy Avatar asked Apr 28 '17 15:04

crackedcornjimmy


People also ask

How use all in LINQ C#?

All Method: The All method of System. LINQ. Queryable class returns a Boolean value if all the elements of the sequence satisfy the provided condition. It returns true if all the elements satisfy the condition otherwise it returns false.

How does Select work in LINQ?

The Select() method invokes the provided selector delegate on each element of the source IEnumerable<T> sequence, and returns a new result IEnumerable<U> sequence containing the output of each invocation.

What is any () in LINQ?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.


1 Answers

You could do another projection using SubThings navigation property:

things = _context.Things.OrderBy(b => b.Name)
.Select(b => new ThingViewModel
{
     Id = b.Id,
     Name = b.Name,
     SubThings =b.SubThings.Select(st=>new SubThingViewModel{Id =st.Id,...}).ToList()
}).ToList();
like image 171
octavioccl Avatar answered Oct 29 '22 16:10

octavioccl