davidrgh
davidrgh

Reputation: 963

How to select a nested object with EF Core and Linq?

Hope someone can help me

I've some tables linked Table1-->Table2-->Table3-->Table4 The relationship is one to many (a record of Table1 has many records of Table2, each one of them has many records of Table3.......).

I have an Id of the Table1 and I need to get the data set of any property of Table4 (only these data). I can use Include and ThenInclude in LINQ to reach the last table, but... how could I select only these data?

I've a code like this one:

_databaseContext.Table1.Where(t1 => t1.Id == id)
            .Include(t1 => t1.Table2Nav)
            .ThenInclude(t2 => t2.Table3Nav)
            .ThenInclude(t3 => t3.Table4Nav)
            .ToList();

This returns to me the complete structure from the first table, but, how could I do a select of specific properties of Table4 (let's suposse that Table4 has a property named "Result" and I need recover a list of all values of "Result" I can reach from the Id of Table1.

Thank's in advance

UPDATE: Here's an example of the structure of the classes:

public class Table1
{
    public int Id { get; set; }
    public List<Tables12> Tables12Nav { get; set; }
}

public class Tables12
{
    public int Id { get; set; }
    public Table1 Table1Nav { get; set; }
    public Table2 Table2Nav { get; set; }
}

public class Table2
{
    public int Id { get; set; }
    public List<Tables12> Tables12Nav { get; set; }
    public List<Table3> Table3Nav { get; set; }
}

public class Table3
{
    public int Id { get; set; }
    public Table2 Table2Nav { get; set; }
    public List<Table4> Table4Nav { get; set; }
}

public class Table4
{
    public int Id { get; set; }
    public Table3 Table3Nav { get; set; }
    public string Result { get; set; }
}

Upvotes: 0

Views: 2061

Answers (1)

wahid-moh
wahid-moh

Reputation: 46

You could use link to sql to get your data :

var TableD = from a in db.TableA
join b in db.TableB on a.Id equals b.TableAId
join c in db.TableC on b.Id equals c.TableBId
join d in db.TableD on c.Id equals d.TableCId
where a.Id == 2
select d;

if you'd like use your code you can retrieve table 4 (table d) as :

var TableD = TableTemp.SelectMany(a => a.TableB.SelectMany(
    b => b.TableC.SelectMany(
        c => c.TableD
)));

Upvotes: 1

Related Questions