2016-11-15 75 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(); 
相关问题