Error with Union in Linq to Entities

c# entity-framework linq

Question

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?

1
12
5/23/2017 12:17:05 PM

Accepted Answer

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
                      })
14
3/6/2014 5:35:12 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow