Reputation: 1071
Is there a way similar to what we can do with linq for left outer join with method based query syntax.
e.g.
var a = from m in context.MainClass
join r in context.RefClass on m.RefID equals r.ID into joinedent
from j in joinedent.DefaultIfEmpty()
select new { m.Name , j.TypeName }
Can I convert this into method based syntax with navigation property default if null
var a = context.MainClass.Select(x=> new {
m.Name
m.RefClass.TypeName // here need default if RefClass is null
})
I can do like (m.RefClass != null)?m.RefClass.TypeName:""
but would like to know if there is a proper way to do this like in above linq.
Thanks
Upvotes: 0
Views: 5103
Reputation: 207
Just use new initialization in DefaultIfEmpty parameter
var a = from m in context.MainClass
join r in context.RefClass on m.RefID equals r.ID on joinedent
from j in joinedent.DefaultIfEmpt(new RefClass())
select new { m.Name , j.TypeName }
Hope the problem will be solve
Upvotes: 1
Reputation: 34783
When EF executes the Linq against the database, the m.RefClass.TypeName would return #null, where the same statement against objects would throw a NullReferenceException.
m.RefClass?.TypeName
should return string.Empty in both cases.
Update: As mentioned the ?. is not allowed in expression trees, however the following does work:
var a = context.MainClass.Select(x=> new {
m.Name
TypeName = m.RefClass.TypeName ?? ""
})
EF expressions will return #null for properties where the child reference is null rather than a null reference exception. However checking the RefClass for null would be safer in case the expression gets copied/moved in a way where it would be run against objects rather than through EF.
On a curious side note I did come across an interesting side-effect while testing this: This only works properly if the relationship between parent and child is mapped as optional. (Obviously) In my case I had an existing test relationship that was set up as "Required" or non-nullable. I'd changed the schema to make the child ID null-able and it did not throw any exceptions, it simply returned no rows
Upvotes: 0
Reputation: 26917
Can you try using Include
?
var a = context.MainClass.Include("RefClass")
.Select(x => new {
m.Name
m.RefClass.TypeName // here need default if RefClass is null
})
Upvotes: 0