Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A type that implements IEnumerable 'System.Collections.Generic.List`1' cannot be initialized in a LINQ to Entities query

I am trying to create object of some class inside the Linq query but gives me an error as set title of the question.

My query is:

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

I have define the list of class in as object inside 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; }
}
like image 930
3 rules Avatar asked Nov 15 '16 10:11

3 rules


2 Answers

Initialise the secondClass List inside your ViewModel constructor:

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

Remember to remove the initialisation from the Linq query.

Edit

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

Edit 2

Your oneViewModel should look something like this:

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

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

The linq query should look like this:

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

Now that you will have a list of oneViewModel objects.

like image 124
Ryan Searle Avatar answered Sep 30 '22 23:09

Ryan Searle


You need to execute query first and then initialize list, e.g.:

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();
like image 38
Pawel Maga Avatar answered Sep 30 '22 23:09

Pawel Maga