简体   繁体   中英

Eagerloading a null in EF core gives an error

How can we handle scenarios when the Include is getting a null that has a ThenInclude for its Child ?

_context.Bakery
.Include(p=>p.Parent) //Parent is null so there is an exception
.ThenInclude(c=>c.Child)
.SingleOrDefaultAsync();

Here in the Bakery class:

public class Bakery
{
    public virtual SomeParent Parent {get;set;}
}

Here in the SomeParent class:

public class SomeParent 
{
    public virtual SomeChildren Child {get;set;}
}

Just add null-forgiving operator "!" to your first include

_context.Bakery
   .Include(p=>p.Parent!) // <--
     .ThenInclude(c=>c.Child)
        .SingleOrDefaultAsync();

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