2016-11-15 43 views
2

我想在Linq查詢中創建一些類的對象,但給我一個錯誤,這個問題。實現IEnumerable'System.Collections.Generic.List`1'的類型不能在LINQ to Entities查詢中初始化

我的查詢是:

List<oneViewModel> workOrderInfoList = (from abc in db.ABC 
    join customer in db.Customers on abc.CustomerId equals customer.CustomerId into customers 
    select new oneViewModel() 
    { 
    CustomerId = abc.CustomerId, 
    OrderNumber = workOrderInfo.OrderNumber, 
    OrderDate = abc.OrderDate, 
    SecondClassList = new List<SecondClass>(), 
    }).ToList(); 

我在AS內部oneViewModel對象定義類的列表。

public class ABC   
{ 
    public DateTime? WorkOrderDate { get; set; } 
    public long CustomerId { get; set; } 

    public string CustomerName { get; set; } 

    public List<SecondClass> SecondClassList { get; set; } 
} 

回答

9

初始化的secondClass列表您ViewModel構造函數中:

Public oneViewModel() 
{ 
    SecondClassList = new List<SecondClass>(); 
) 

記得從Linq查詢中刪除初始化。

編輯

List<oneViewModel> workOrderInfoList = (from abc in db.ABC 
    join customer in db.Customers on abc.CustomerId equals customer.CustomerId into customers 
    select new oneViewModel() 
    { 
     CustomerId = abc.CustomerId, 
     OrderNumber = workOrderInfo.OrderNumber, 
     OrderDate = abc.OrderDate, 
     SecondClassList = abc.SecondClassList 
    }).ToList(); 

編輯2

oneViewModel應該是這個樣子:

public class oneViewModel 
{ 
    public oneViewModel 
    { 
     SecondClassList = new List<SecondClass>(); 
    } 

    Public List<SecondClass> SecondClassList { get; set; } 
} 

LINQ查詢應該是這樣的:

List<oneViewModel> workOrderInfoList = (from abc in db.ABC 
join customer in db.Customers on abc.CustomerId equals customer.CustomerId into customers 
select new oneViewModel() 
{ 
    CustomerId = abc.CustomerId, 
    OrderNumber = workOrderInfo.OrderNumber, 
    OrderDate = abc.OrderDate 
}).ToList(); 

現在您將擁有一個oneViewModel對象的列表。

+0

我怎樣才能在一個一舉兩得?我已經在ABC內部公佈了第二個班級名單。 –

+0

查看更新答案。 –

+0

感謝Ryan的迴應,但我不知道我該如何聲明並用它在構造函數中進行設置。我已經接受了帕維爾的回答。 –

1

您需要先執行查詢,然後初始化列表,例如:

List<oneViewModel> workOrderInfoList = (from abc in db.ABC 
    join customer in db.Customers on abc.CustomerId equals customer.CustomerId into customers).ToList() 
    Select(n => new oneViewModel() 
    { 
    CustomerId = n.CustomerId, 
    OrderNumber = workOrderInfo.OrderNumber, 
    OrderDate = n.OrderDate, 
    SecondClassList = new List<SecondClass>(), 
    }).ToList(); 
相關問題