我的视图模型中的大多数值都已成功返回,但在我更新模型类后,其中两个值(与数据库中的其他表相关联)返回空值,即使我没有更改分配它们的方式. 我已经意识到问题出在这句话上:
Vehicles = utc.Vehicles.OrderByDescending(v => v.DateCreated).Take(10).ToList()
它不包括车辆型号和制造商。我正在寻找一种方法来将此语句更改为:
Vehicles = utc.Vehicles.Include(v => v.Model).Include(v => v.Model.Manufacturer).OrderByDescending(v => v.DateCreated).Take(10).ToList()
但它会引发错误并且无法编译。
有人可以帮忙吗?
编辑 这是我的代码。对于控制器:
public ActionResult Index()
{
var home = new HomeViewModel
{
latestVehiclesViewModel = new LatestVehiclesViewModel
{
Vehicles = utc.Vehicles.Include("Model").Include("Manufacturer")
.OrderByDescending(v => v.DateCreated)
.Take(10)
.ToList()
},
searchViewModel = new SearchViewModel
{
Manufacturers = utc.Manufacturers.ToList(),
//Models = utc.Models.ToList(),
}
};
return View(home);
}
对于模型模型:
public class Model
{
public int ModelId { get; set; }
public int ManufacturerId { get; set; }
public string Name { get; set; }
public List<Vehicle> Vehicles { get; set; }
public Manufacturer Manufacturer { get; set; }
}