Linq查询以在连接对象上包含项目

时间:2016-03-08 20:16:37

标签: c# entity-framework linq

我正在尝试使用包含子对象的Linq查询来获取对象集合。我可以在主表上做一个包含并获得结果。但是如果我在我加入的其中一个表上做了一个include,我就不会得到include应该返回的对象。

以下是我的模特:

public class RequestReviewViewModel
{
    public Guid RequestId { get; set; }
    public Guid ResourceToReviewId { get; set; }
    public Guid ReviewRequiredId { get; set; }
    public ReviewRequired ReviewRequired { get; set; }
}

public class Required : BaseEntity
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public Guid RequiredId { get; set; }

    [Display(Name = "Review Name")]
    public int ReviewNameId { get; set; }
    [ForeignKey("ReviewNameId")]
    public ReviewName ReviewName { get; set; }
}

这是我正在尝试的linq查询。行Required.Include(revr => revr.ReviewName)似乎没有做任何事情:

var requests = (from req in Request.Include(rr => rr.Resource)
    join revreq in Required.Include(revr => revr.ReviewName) 
        on req.ReviewRequiredId equals revreq.RequiredId
    where req.IsActive
    select new RequestReviewViewModel
    {
        RequestId = req.RequestId,
        ResourceToReviewId = req.ResourceToReviewId,
        ReviewRequiredId = req.ReviewRequiredId,
        Required = revreq
    };

requests.FirstOrDefault().Required.ReviewName.Dump();

虽然requests.FirstOrDefault().Required.ReviewNameId有值,但ReviewName对象为空。这种关系在数据库中,由Code First创建。

1 个答案:

答案 0 :(得分:2)

您的ReviewName未声明virtual,可启用预先加载/延迟加载(并自动更改跟踪完成)。添加virtual,它应该有效:

public virtual ReviewName ReviewName { get; set; }