【问题标题】:Load related entities from a Collection in Entity Framework从实体框架中的集合加载相关实体
【发布时间】:2013-07-11 15:22:41
【问题描述】:

如何从已加载的集合中加载相关实体:

收藏:

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

特点:

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

关键字:

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

我需要为广告中的所有功能加载实体关键字。

谢谢

【问题讨论】:

    标签: c# asp.net-mvc linq entity-framework


    【解决方案1】:

    在您的存储库类中尝试:

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

    【讨论】:

    • 您好,谢谢,这里的问题是我使用带有 Get、Ad 等方法的存储库。
    • @Patrick,主要思想是.Include(ad =&gt; ad.Features.Select(feature =&gt; feature.Keyword))。或者您能举例说明您的存储库是如何实现的吗?
    猜你喜欢
    • 2014-10-23
    • 1970-01-01
    • 2011-04-09
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    • 2011-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多