MVC4 EF4.3子对象未从DB中提取

时间:2012-06-01 10:06:28

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

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

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

I've looked at the answer which contained this link但是我正在努力让这个工作起作用。

我的广告系列存储库会返回一个广告系列。它按预期返回审核列表,但审核对象中没有注释或CampaignAction。我需要做些什么特别的事情来告诉DB拔出所有级联对象吗?

感谢您的帮助

尼尔

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

1 个答案:

答案 0 :(得分: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);