此连接的 EF Linq 查询的正确语法是什么

What is the right syntax for this joined EF Linq query

我正在尝试查询 returns 为我的 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>()
                };

这是我的视图模型

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

我得到的错误是(红色波浪线在 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>'

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

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

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