简体   繁体   中英

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?

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
                      })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM