Andez
Andez

Reputation: 5858

Linq - Selecting or iterating through all grandchildren with VB.NET

All,

I am experimenting with Linq and Entity Framework (athough I am using nHydrate) in VB.NET. Lets say I have 3 tables as follows:

Diagram

So Table1 is the top level grandparent which has a number of records/entities.

I want to select all of Table3 records/entities that are related to a specific Table1 instance. I want to do this as part of some search functionality.

I want to take an instance of Table1 as my starting point, i.e.

Public Class MySearch

    Private _lookUnder As System.Data.Objects.DataClasses.EntityObject

    Public Sub Search() 
        ...
        CType(_lookUnder, Table1) ' ???? need to linq here ????
        ...
    End Sub
End Class

Can this be done completely with Linq? C# answers are welcome.

I've tried looking at this but didn't help too much.

Thanks,

Andez

Upvotes: 0

Views: 500

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156624

Ideally, you should have access to the context, making something like this possible (C#):

var relatedTable3s = context.Table3s.Where(t3 => t3.Table2.Table1.id == _lookUnder.id);

I suppose something like this might work, too:

var relatedTable3s =
    from t2 in _lookUnder.Table2s.AsQueryable()
    from t3 in t2.Table3s
    select t3;

... otherwise written as:

var relatedTable3s = _lookUnder.Table2s.AsQueryable()
    .SelectMany(t2 => t2.Table3s);

Upvotes: 2

Related Questions