Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ include multiple children

I have a construction that store databases metadata

public class Database {
    public string ConnectionString { get; set; }
    public virtual ICollection<Table> Tables { get; set; }
}

public class Table {
    public string TableName { get; set; }
    public virtual ICollection<ForeingKey> ForeingKeys { get; set; }
    public virtual ICollection<Field> Fields { get; set; }
}

I would like to retrieve all database related data in one only query with LINQ I can query tables and one child entity from databases

            var qry = from d in context.Databases
                         .Include(x => x.Tables.Select( c => c.Fields))
                      select d;

But, how can I read two childs from Tables collection? Something like this

 var qry = from d in context.Databases
             .Include(x => x.Tables.Include(t => t.Fields).Include(t => t.ForeingKeys))
           select d;
like image 929
mnieto Avatar asked Jun 19 '14 14:06

mnieto


2 Answers

var qry = from d in context.Databases
    .Include("Tables.Fields")
    .Include("Tables.ForeingKeys")
  select d;

EF will automatically include tables for you and then include those navigation properties in the query.

like image 179
Tacoman667 Avatar answered Nov 07 '22 10:11

Tacoman667


Another way to achieve the same is

        var qry = from d in context.Databases
                      .Include(x => x.Tables)
                      .Include(x => x.Tables.Select(c => c.Fields))
                      .Include(x => x.Tables.Select(f => f.ForeingKeys))
                  select d;

I prefer do not use literals.

like image 23
mnieto Avatar answered Nov 07 '22 12:11

mnieto