LINQ include multiple childs

c# entity-framework linq

Question

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;
1
8
6/19/2014 2:49:41 PM

Accepted Answer

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.

7
6/19/2014 2:53:01 PM

Popular Answer

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow