1

我无法从数据库中获取所有数据,而且我不完全确定我做错了什么,几乎所有这些对我来说都是新的。

我搜索了 SO 并发现以下问题似乎与我的非常相似 - Repository Pattern for Entity Framework and Children Objects

我已经查看了包含此链接的答案,但我正在努力让它发挥作用。

我有我的活动存储库,它返回一个活动。它按预期返回审核列表,但审核中没有评论或 CampaignAction。我需要做一些特别的事情来告诉数据库拉出所有级联对象吗?

谢谢你的帮助

尼尔

    public override Campaign Get(int id)
    {
        var query = Context.Campaigns.Include(x => x.Audits)
                                     .FirstOrDefault(c => c.CampaignId == id);
        if (query != null) 
            Logger.Trace(query.ToString());
        return query;
    }

我有我的竞选班

public class Campaign
{
    public Campaign()
    {
        Audits = new Collection<Audit>();
    }

    public int CampaignId { get; set; }

    [StringLength(40, ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "CampaignModel_Name_StringLength")]
    [Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "CampaignModel_Name_Required")]
    [Display(Name = "CampaignModel_Name", ResourceType = typeof(Resources.Resources))]
    public string Name { get; set; }

    public ICollection<Audit> Audits { get; set; }
}

还有我的审计课

public class Audit
{
    public Audit()
    {
        Comments = new Collection<Comment>();
    }

    public int AuditId { get; set; }

    [Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "Audit_CampaignAction_Required")]
    [Display(Name = "Audit_CampaignAction", ResourceType = typeof(Resources.Resources))]
    public CampaignAction Action { get; set; }

    [Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "Audit_UserName_Required")]
    [Display(Name = "Audit_UserName_Content", ResourceType = typeof(Resources.Resources))]
    public string UserName { get; set; }

    [Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "Audit_TimeStamp_Required")]
    [Display(Name = "Audit_TimeStamp", ResourceType = typeof(Resources.Resources))]
    public DateTime TimeStamp { get; set; }

    public ICollection<Comment> Comments { get; set; }

    [JsonIgnore]
    public virtual ICollection<Campaign> Campaigns { get; set; }
}
4

1 回答 1

2

只要您使用预先加载,您就必须调用Include()您希望从数据库加载的所有实体。此规则适用于子实体(审核),也适用于孙实体(操作和评论)。

通常你会使用简单的点表示法来包含孙子实体,但如果子实体是一个集合,则使用该Select()方法有一个特殊的语法。

您的查询应如下所示

var query = Context.Campaigns.Include(x => x.Audits)
                             .Include(x => x.Audits.Select(a => a.Comments))
                             .Include(x => x.Audits.Select(a => a.Action))
                             .FirstOrDefault(c => c.CampaignId == id);
于 2012-06-01T10:52:06.673 回答