使用linq查询嵌套的视图模型

时间:2015-10-19 01:45:53

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

我有以下viewmodels:

public class CustomerViewModel
{        
    public string FirstName { get; set; }       
    public string LastName { get; set; }       
    public string Email { get; set; }
}

public class InvoiceViewModel
{
    public int InvoiceID { get; set; }          
    public int Quantity { get; set; }       
    public double Price { get; set; }        
    public double Tax { get; set; }
}

public class CombinedViewModel
{
    public InvoiceViewModel InvoiceViewModel { get; set; }
    public CustomerViewModel CustomerViewModel { get; set; }

}

我尝试使用linq查询CombinedViewModel但是无法访问嵌套视图模型的变量。

 var invoice = (from i in db.Invoices
                           select new CombinedViewModel
                           {             
                               //Not allowing me to access variables. 
                               //Not in context error                
                               InvoiceViewModel.Quantity = i.Quantity
                       });

2 个答案:

答案 0 :(得分:1)

'嵌套'视图模型InvoiceViewModelCustomerViewModel是未自动实例化的对象。您需要自己创建它们:

var invoice = (from i in db.Invoices
    select new CombinedViewModel
    {
        InvoiceViewModel = new InvoiceViewModel {
            Quantity = i.Quantity
        },
        CustomerViewModel = new CustomerViewModel {
            // whatever goes here
        }
    });

就个人而言,我会添加某种构造函数或类型转换来获取数据模型对象并生成它们的视图模型,我当然建议您将成员名称更改为与其类型不同以生成代码更容易阅读......但我想这些只是风格选择。

例如,假设您有一个InvoiceModel类,如下所示:

public class InvoiceModel
{
    public int InvoiceID { get; set; }
    public int Quantity { get; set; }
    public double Price { get; set; }
    public double TaxRate { get; set; }
}

您可以像这样添加隐式转换:

public static implicit operator InvoiceViewModel(InvoiceModel model)
{
    return new InvoiceViewModel
    {
        InvoiceID = model.InvoiceID,
        Quantity = model.Quantity,
        Price = model.Price,
        Tax = model.Price * model.TaxRate
    };
}

现在你可以做到:

from i in db.Invoices
select new CombinedViewModel 
    { 
        InvoiceViewModel = i, 
        CustomerViewModel = new CustomerViewModel() 
    }

或者,将此构造函数添加到InvoiceViewModel

public InvoiceViewModel(InvoiceModel model)
{
    InvoiceID = model.InvoiceID;
    Quantity = model.Quantity;
    Price = model.Price;
    Tax = model.Price * model.TaxRate;
}

然后做:

from i in db.Invoices
select new CombinedViewModel 
    { 
        InvoiceViewModel = new InvoiceViewModel(i), 
        CustomerViewModel = new CustomerViewModel() 
    }

答案 1 :(得分:0)

尝试以下代码

var invoice = (from i in db.Invoices
                           select new CombinedViewModel
                           {             
                               //Not valid                  
                               InvoiceViewModel=new InvoiceViewModel{Quantity = i.Quantity}
                   });