简体   繁体   中英

C# EF DefaultIfEmpty with Where().Select()

Is there a way similar to what we can do with linq for left outer join with method based query syntax.

eg

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM