ViewModel向View返回null值的问题

时间:2013-06-02 19:34:22

标签: linq entity-framework linq-to-sql asp.net-mvc-4 entity-framework-5

我的viewmodel中的大多数值都被成功返回,但是在我更新了我的模型类之后,其中两个值(与数据库中的其他表绑定)返回空值,即使我没有更改我指派他们。我已经意识到问题在于这个陈述:

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);
    }

对于模型Model:

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; }
}

2 个答案:

答案 0 :(得分:2)

我的EF5不允许我将表达式作为参数传递给DbSet()。包含。

试试这个:

Vehicles = utc.Vehicles.Include("Model").Include("Manufacturer")
            .OrderByDescending(v => v.DateCreated)
            .Take(10)
            .ToList()

答案 1 :(得分:0)

我自己修理了......新的错误是我的错,应该是Include(“Model.Manufacturer”)......我接受了Quinton Bernhardt的答案,因为这是帮助我在第一名......谢谢。