简体   繁体   中英

Load related entities from a Collection in Entity Framework

How do I load related entities from an already loaded Collection:

The Collection:

public class Ad
{
    // Primary properties
    [Key]
    public int Id { get; set; }
    private ICollection<Feature> _features;
    public virtual ICollection<Feature> Features
    {
      get { return _features ?? (_features = new HashSet<Feature>()); }
      set { _features = value; }
    }
}

The Feature:

public class Feature
{
    // Primary properties
    public int Id { get; set; }
    public string Name { get; set; }

    // Navigation properties
    public virtual ICollection<Ad> Ads { get; set; }
    public Keyword Keyword { get; set; }
}

The Keyword:

public class Keyword
{
    // Primary properties
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsActive { get; set; }
}

I need to load the entity Keyword for all the Features in an Ad.

Thanks

In your repository class try:

public Ad GetAd(int id)
{
     return _database.Set<Ad>().Include(ad => ad.Features.Select(feature => feature.Keyword)).FirstOrDefault(ad => ad.Id == id);
}

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