[asp.net-mvc]使用 linq 查询嵌套的 viewmodel

发布时间: 2017/3/25 10:39:54
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我有下列视图︰

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,但遇到了问题访问嵌套 viewmodel 的变量。

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

解决方法 1:

嵌套 viewmodel 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() 
    }
官方微信
官方QQ群
31647020