这个加入的EF Linq查询的正确语法是什么

时间:2016-03-11 01:15:29

标签: asp.net-mvc entity-framework linq asp.net-mvc-viewmodel

我正在尝试获取一个查询,该查询返回为我的ViewModel正确格式化的所有内容,因此我不必手动从实体模型中复制所有内容。我有这个Linq查询给我一个错误。 :

var query = from i in context.Invoices 
            join l in context.LineItems on i.InvoiceID equals l.InvoiceID into il
            where i.InvoiceID == id
            select new InvoiceViewModel()
                {
                InvoiceID = i.InvoiceID,
                CustomerID = i.CustomerID,
                InvoiceNote = i.Note,
                InvoiceDate = i.InvoiceDate,
                Terms = i.Terms,
                LineItems = il.ToList<LineItemViewModel>()
                };

这是我的ViewModel

 public class InvoiceViewModel        {
    public int InvoiceID { get; set; }
    public int CustomerID { get; set; }
    public string InvoiceNote { get; set; }
    public DateTime InvoiceDate { get; set; }
    public string Terms { get; set; }
    public virtual ICollection<LineItemViewModel> LineItems { get; set; }
    }

public class LineItemViewModel        {
    public int LineItemID { get; set; }
    public int InvoiceID { get; set; }
    public int Quantity { get; set; }
    public string Item { get; set; }
    public decimal Amount { get; set; }
    public string LineItemNote { get; set; }
    }

我得到的错误是(红色squigly在LineItems = il.ToList()中的il下)

'IEnumerable<LineItem>' does not contain a definition for 'ToList' and the best extension method overload 'Enumerable.ToList<LineItemViewModel>(IEnumerable<LineItemViewModel>)' requires a receiver of type 'IEnumerable<LineItemViewModel>'

我(有点,有点,有点)理解。那么这个的正确语法是什么?

1 个答案:

答案 0 :(得分:1)

您需要从LineItemViewModel实体显式初始化LineItem个实例。你可能最好把它写成相关的子查询而不是连接:

var query = 
        from i in context.Invoices 
        where i.InvoiceID == id
        select new InvoiceViewModel()
        {
            InvoiceID = i.InvoiceID,
            CustomerID = i.CustomerID,
            InvoiceNote = i.Note,
            InvoiceDate = i.InvoiceDate,
            Terms = i.Terms,
            LineItems = 
            (
                from li in context.LineItems
                where li.InvoiceID == i.InvoiceID
                select new LineItemViewModel
                {
                    LineItemID = li.LineItemID, 
                    InvoiceID = li.InvoiceID,
                    Quantity = li.Quantity,
                    Item = li.Item,
                    Amount = li.Amount,
                    LineItemNote = li.LineItemNote,
                }
            ).ToList()
        };