要在具有MVC的View模型中使用的复杂DTO

时间:2013-11-29 16:13:18

标签: c# asp.net-mvc linq nhibernate

我有以下内容:

class CarInspection
{
    public CarInspectionAgenda Agenda {get;set;}
    public string Description {get;set;}
    ...
}

class CarInspectionAgenda 
{
    public IList<DummyA> DummyAList {get;set;} 
    public string Name {get;set;}
    ...    
}

class DummyAList 
{
    public DummyB DummyB {get;set;}
    ...
}

class DummyB 
{
    public string Name {get;set;}
   ...
}

好的,所以在我的CarInspection视图中,我创建了一个CarInspectionViewModel。我需要使用DummyB Names ...

显示自定义格式化字符串

所以,我创建了ViewModel:

public CarInspectionViewModel
{
    public string Description {get;set;}
    public CarInspectionAgendaViewModel Agenda {get;set;}

}

public CarInspectionAgendaViewModel
{
    public string Name {get;set;}
    public IList<string> DummyANameList {get;set;} 
}

我尝试过类似的东西:

var list = carInspectionRepository.GetAll().Select(x => new CarInspectionViewModel()
{
     Id = x.Id,
     Description = x.Description,
     Agenda = new AgendaFiscalizacaoVM
     {
          Id = x.CarInspectionAgenda.Id,
          Name = x.CarInspectionAgenda.Name,
          DummyANameList = x.CarInspectionAgenda.DummyAList.Select(y => y.DummyB.Name)
     }
}); 

我在DummyANameList中得到了一些奇怪的结果......我认为LINQ有问题......有什么帮助吗?

由于

1 个答案:

答案 0 :(得分:0)

简答:

您在LINQ语句中缺少.ToList()

var list = carInspectionRepository.GetAll().Select(x => new CarInspectionViewModel()
{
    Id = x.Id,
    Description = x.Description,
    Agenda = new AgendaFiscalizacaoVM
    {
        Id = x.CarInspectionAgenda.Id,
        Name = x.CarInspectionAgenda.Name,
        DummyANameList = x.CarInspectionAgenda
            .DummyAList
            .Select(y => y.DummyB.Name)
            .ToList()
    }
}).ToList(); 


更长的回答:

LINQ语句(在大多数情况下)不会立即进行评估。评估被推迟到稍后使用LINQ创建的代码变量中的某个地方。如果无法成功评估语句,LINQ(在大多数情况下再次)将在您使用此类变量的行中抛出异常。致电ToList()ToArray() will evaluate LINQ statement immediately

我想(因为我看不到完整的代码)DummyAList没有立即从数据库加载(例如LazyLoad中的NHibernate)以及您使用结果列表的地方在数据库会话范围之外,因此LINQ评估失败。