Selecting a null value in a select select clause in EF5

I am trying to select the data I need for a simple anonymous type to serialize data for a Json request.

using (var dbContext = new DataContext()) { var vals = dbContext.Primaries.Select(p => new { Name = p.Name, Secondary = p.SecondaryId.HasValue ? new { Name = p.Secondary.Name } : null }); } 

but when I call the enumerator on vals, I get the following exception

 Unable to create a null constant value of type 'Anonymous type'. Only entity types, enumeration types or primitive types are supported in this context. 

I really need Secondary be null if the foreign key is null. How can I get the anonymous null value directly from the select statement.

My solution is to be able to serialize the resulting data directly without processing an intermediate data set.

+4
source share
2 answers

You can get around this by always returning an anonymous object, where an anonymous object can have null properties.

 using (var dbContext = new DataContext()) { var vals = dbContext.Primaries.Select(p => new { Name = p.Name, Secondary = new { Name = p.SecondaryId.HasValue ? p.Secondary.Name : null } }); } 

And if you really want to make Secondary null, if p.SecondaryId is null, you can add the following.

 //ToList allows you to work with LINQ to Objects rather than Linq to Entities. //However, you'll generally want to call ToList() last for performance reasons. var valsCleaned = vals.ToList() .Select(v => { if(v.Secondary.Name == null) { v.Secondary == null; } return v; }); 
0
source

I do not have a โ€œsolutionโ€ as such. To get around this problem, I simply projected the entire secondary object. I am not happy with this decision.

 using (var dbContext = new DataContext()) { var vals = dbContext.Primaries.Select(p => new { Name = p.Name, Secondary = p.Secondary }); } 

Obviously, projecting an entire object is akin to "SELECT *" - this is bad practice. And this may not work for you, depending on your actual request.

0
source

Source: https://habr.com/ru/post/1492843/


All Articles