开发者

Nested dictionary nullreferenceexception using linq and entity framework

开发者 https://www.devze.com 2023-03-30 09:14 出处:网络
I\'m trying to populate a dictionary using a nested select, and I get nullreference exception, since objects from TableC might not exists.

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

精彩评论

暂无评论...
验证码 换一张
取 消