简体   繁体   中英

Include navigation prop on ICollection

I have this Keuring class and I have a problem including a navigation item on the Testresultaten collection property using linq.

public partial class Keuring
{
    public Keuring()
    {
        Testresultaten = new HashSet<Testresultaten>();
    }

    //Simple properties here

    //Complex properties below
    public virtual ICollection<Testresultaten> Testresultaten { get; set; }
    public virtual Gereedschap Gereedschap { get; set; }
}

Here is the Testresultaten class:

public partial class Testresultaten
{
    //Simple properties here

    //Complex properties below
    public virtual Test Test { get; set; }
    public virtual Keuring Keuring { get; set; }
}

Here is the Gereedschap class:

public partial class Gereedschap
{
    public Gereedschap()
    {
        Keuring = new HashSet<Keuring>();
    }

    //Simple properties here

    //Complex properties below
    public virtual ICollection<Keuring> Keuring { get; set; }
    public virtual Debiteur Debiteur { get; set; }
}

This statement works fine:

var keuringEntry = db.Keuring.Include(item => item.Gereedschap).Include(item => item.Testresultaten).SingleOrDefault(item => item.key = "keyvalue");

But when I add an extra Include like this:
Include(item => item.Testresultaten.Select(subItem => subItem.Test))
the statement gives an error:

var keuringEntry = db.Keuring.Include(item => item.Gereedschap).Include(item => item.Testresultaten.Select(subItem => subItem.Test)).SingleOrDefault(item => item.key = "keyvalue");

Error: The property expression 'x => {from Testresultaten subItem in [x].Testresultaten select [subItem].Test}' is not valid. The expression should represent a property access: 't => t.MyProperty'.

The Test var in the Testresultaten class is a property and not a field. What am I doing wrong? And it is accesable just like Gereedschap is in Keuring

You need to do it as shown below.

var keuringEntry = db.Keuring.Include(item => item.Gereedschap)
                  .Include(item => item.Testresultaten)
                       .ThenInclude(subItem => subItem.Test)
                  .FirstOrDefault(item => item.key = "keyvalue");

Refernce : Including multiple levels

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