In my application the structure looks like this:
public class Route
{
[Key]
public int RouteId {get; set;}
public Address virtual AddressA {get; set;}
public Address virtual AddressB {get; set;}
}
public class Address
{
[Key]
public int AddressId {get; set;}
public string Name {get; set;}
}
and
public class DbConnection : DbContext
{
public DbSet<Route> Routes{get; set;}
public DbSet<Address> Addresses{get; set;}
}
I take the data like this:
public ActionResult GetList()
{
using(DbConnection db = new DbConnection)
{
var query = db.Routes.ToList();
}
return PartialView(query);
}
and then display the data:
@foreach (var r in Model)
{
<div>@r.AddressA.Name - @r.AddressB.Name</div>
}
However the problem is that the View/PartialView is rendered after the using brackets close so it tries to access AddressA's Name and this gives me an error because the table was not loaded full. Yes, I can do:
public ActionResult GetList()
{
using(DbConnection db = new DbConnection)
{
var query = db.Routes.Include("Address").ToList();
}
return PartialView(query);
}
However, when I make this a tiny bit more complex query, the code starts getting really ugly with all the includes. Is there some way to overcome this so with one simple line of code or something less ugly than .Include("A").Include("B").Include("X.Y.Z")?