在我的应用程序中,结构如下所示:
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;}
}
和
public class DbConnection : DbContext
{
public DbSet<Route> Routes{get; set;}
public DbSet<Address> Addresses{get; set;}
}
我拿这样的数据:
public ActionResult GetList()
{
using(DbConnection db = new DbConnection)
{
var query = db.Routes.ToList();
}
return PartialView(query);
}
然后显示数据:
@foreach (var r in Model)
{
<div>@r.AddressA.Name - @r.AddressB.Name</div>
}
但是问题是在括号关闭后呈现 View/PartialView,using
因此它尝试访问 AddressA 的名称,这给了我一个错误,因为表没有加载满。是的,我可以这样做:
public ActionResult GetList()
{
using(DbConnection db = new DbConnection)
{
var query = db.Routes.Include("Address").ToList();
}
return PartialView(query);
}
但是,当我使这个查询变得稍微复杂一点时,所有包含的代码都开始变得非常难看。有没有办法用一行简单的代码或不那么难看的东西来克服这个问题.Include("A").Include("B").Include("X.Y.Z")
?