Find data from related tables

2

I know that to return the values of a directly related entity in the database is done with LINQ:

List<Usuario> lista = banco.Usuario.Include("Tipo").ToList();

But how do I get the data back from another table related to the "Type" table? For example, the "Type" table has a relationship with the "Situation" table that the "User" table does not know.

In short, the relationship looks like this: "User" with "Type" and "Type" with "Location". I need the "Situation" data coming along too.

DbContext

public partial class BancoDeHorasEntities : DbContext
{
    public BancoDeHorasEntities()
        : base("name=BancoDeHorasEntities")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public DbSet<Usuario> Usuario { get; set; }
    public DbSet<Tipo> Tipo { get; set; }
    public DbSet<Situacao> Situacao { get; set; }
    public DbSet<sysdiagrams> sysdiagrams { get; set; }
}

User.cs

public partial class Usuario
{
    public int Id { get; set; }
    public Nullable<int> IdPessoa { get; set; }
    public string Descricao { get; set; }
    public Nullable<int> IdTipo { get; set; }

    public virtual Tipo Tipo { get; set; }
}

Type.cs

 public partial class Tipo
 {
    public Tipo()
    {
        this.Usuarios = new HashSet<Usuario>();
    }

    public int Id { get; set; }
    public Nullable<int> IdSituacao { get; set; }
    public string Descricao { get; set; }

    public virtual Situacao Situacao { get; set; }
    public virtual ICollection<Usuario> Usuarios { get; set; }
}

Situation.cs

public partial class Situacao
{
    public Situacao()
    {
        this.Tipos = new HashSet<Tipo>();
    }

    public int Id { get; set; }
    public string Nome { get; set; }
    public string Descricao { get; set; }

    public virtual ICollection<Tipo> Tipo { get; set; }
}

Database Modeling

Inshort,theproblemis:howtoobtainthedatafromthe"Situation" table when searching for "User".

    
asked by anonymous 26.05.2015 / 14:06

1 answer

3

You can add other include to your LINQ expression

List<Usuario> lista = banco.Usuario
                           .Include("Tipo")
                           .Include("NomeTabela")
                           .ToList();

Edit

After viewing your entities:

Using LINQ:

List<Usuario> lista = banco.Usuario.Include(u => u.Tipo.Situacao).ToList;  

Using string:

List<Usuario> lista = banco.Usuario.Include("Tipo.Situacao").ToList;

Other examples

    
26.05.2015 / 14:40