Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error with Union in Linq to Entities

I'm having problem in a query where I want to merge 2 lists.

I want to merge records from tables Places and Locations into View Model property Places.

Fruits = (from e in db.Fruits
           where !e.Excluded
           select new FruitViewModel()
           {
               CodFood = e.CodFood,
               Name = e.Name,
               Color = e.Color,
               Places = (from p in e.Places
                          where !p.Excluded
                          select new FruitViewModel()
                          {
                              CodPlace = p.CodPlace,
                              Name = p.Name
                          }).Union(
                          from r in e.Locations
                          where !r.Excluido
                          select new FruitViewModel()
                          {
                              CodLocation = r.CodLocation,
                              Name = p.Name
                          })
           }),

but it gives me:

System.NotSupportedException: The type 'Project.ViewModel.Fruits.FruitsViewModel' appears in two structurally incompatible initializations within a single LINQ to Entities query. A type can be initialized in two places in the same query, but only if the same properties are set in both places and those properties are set in the same order.

I can merge after Linq execution as this answer, but I want to keep things simple not changing too much this code, if possible - query before deferred execution.

How can I resolve this?

like image 995
Andre Figueiredo Avatar asked Mar 06 '14 17:03

Andre Figueiredo


1 Answers

Based on the error message it seems to be a problem with your initialization of FruitViewModel. Try this:

           Places = (from p in e.Places
                      where !p.Excluded
                      select new FruitViewModel()
                      {
                          CodLocation = "",
                          CodPlace = p.CodPlace,
                          Name = p.Name
                      }).Union(
                      from r in e.Locations
                      where !r.Excluido
                      select new FruitViewModel()
                      {
                          CodLocation = r.CodLocation,
                          CodPlace = "",
                          Name = p.Name
                      })
like image 195
Craig W. Avatar answered Oct 22 '22 01:10

Craig W.