Lasse Edsvik
Lasse Edsvik

Reputation: 9298

Nested query using Linq with ToDictionary

I'm having problems with this query using entity framework 4:

List<SomeResult> test = (from a in _entities.TableA
                         select new SomeResult
                         {
                            TestB = a.TableB.Name,
                            TestCDict = a.TableC.ToDictionary(x => x.SomeKey, x => x.SomeValue)
                          }).ToList();

It gives this error:

"Cannot compare elements of type 'System.Data.Objects.DataClasses.EntityCollection`1'. Only primitive types (such as Int32, String, and Guid) and entity types are supported."

How can I redo this query so it'll work? from a in _entities.TableA from c in a.TableC ....ToDictionary(.. ?

/Lasse

Upvotes: 1

Views: 2133

Answers (1)

Vladimir Perevalov
Vladimir Perevalov

Reputation: 4157

The problem is, that you are doing query against database. And LINQ provider that you are using, actually don't execute any of the operations, that you have written. It only tryes to translate all your code in Select into database query. Obviously, it can't parse really complex statents, like you have written with ToDictionary(). You can simply load all data from entities into memory, and then do all your dictionary stuff. Then your code will actually be executed, and should work. Like:

List<SomeResult> test = from a in (from aa in _entities.TableA).AsEnumerable())
                         select new SomeResult
                         {
                            TestB = a.TableB.Name,
                            TestCDict = a.TableC.ToDictionary(x => x.SomeKey, x => x.SomeValue)
                          }).ToList();

Of course you can use DB side filtering in the inner query (before AsEnumerable()) to narrow amount of data loaded into memory.

Upvotes: 3

Related Questions