Nested dictionary nullreferenceexception using linq and entity framework
I'm trying to populate a dictionary using a nested select, and I get nullreference exception, since objects from TableC might not exists.
List<SomeResult> test = (from a in _entities.TableA
select new SomeResult
开发者_StackOverflow中文版{
TestB = a.TableB.Name,
TestCDict = a.TableC.ToDictionary(x => x.SomeKey, x => x.SomeValue)
}).ToList();
How do I fix so TestCDict can be null?
/Lasse
Change it to this:
TestCDict = a.TableC == null ? null
: a.TableC.ToDictionary(x => x.SomeKey, x => x.SomeValue)
Or to this, if you want an empty dictionary instead of null in TestCDict
:
TestCDict = a.TableC == null ? new Dictionary<TypeOfKey, TypeOfValue>()
: a.TableC.ToDictionary(x => x.SomeKey, x => x.SomeValue)
精彩评论