10

我正在尝试使用 EF5 代码优先执行数据库查找。基本结构和表关系如下;

public partial class Member
{
    public int    RecordID {get; set;}
    public string Name     {get; set;}
    ...etc.
    public virtual ICollection<MemberLink> MasterLinks {get; set;}
    public virtual ICollection<MemberLink> SlaveLinks {get; set;}
    public virtual ICollection<Message>    ReceivedMessages {get; set;}
    public virtual ICollection<Message>    SentMessages {get; set;}
}

public partial class MemberLink
{
    public int            RecordID     {get; set;}
    public virtual Member MasterMember {get; set;}
    public virtual Member SlaveMember  {get; set;}
    ...etc.
}

public partial class Message
{
    public int            RecordID  {get; set;}
    public virtual Member Sender    {get; set;}
    public virtual Member Recipient {get; set;}
    ...etc.
}

现在,我尝试执行的查询是使用MemberLinkRepository,看起来像;

public IList<MemberLink> GetMasterLinks(int p_MemberID)
{
    return Get()
           .Include ( memberLink => memberLink.MasterMember )
           .Include ( memberLink => memberLink.SlaveMember )
           .Include ( memberLink => memberLink.MasterMember.ReceivedMessages
                      .Where(
                      msg => msg.Sender.RecordID == memberLink.SlaveMember.RecordID) )
           .Where ( memberLink => memberLink.MasterMember.RecordID == p_MemberID)
           .ToList();

除了 EF 似乎不喜欢嵌套的 Where。我可以将其拆分为 2 个单独的存储库调用(实际上,看起来我可能必须这样做),但为了减少对数据库的调用,我试图一口气完成它。有谁知道我如何在一个查询中实现这一目标?

我希望代码说明了我正在尝试做的事情......如果没有,我会尝试更好地解释一下。

4

1 回答 1

23

简短的回答是否定的,EF 不会让你使用Include().

如果它允许您这样做,请考虑结果:在一种情况下,您MemberLink.MasterMember.ReceivedMessages将完全填充,在另一个看起来相同的对象MemberLink.MasterMember.ReceivedMessages上实际上是消息的子集!如果您尝试添加到 ReceivedMessages 会发生什么?如果添加与过滤器不匹配怎么办?这是一袋伤害。

答案是使用预测:

public IList<MemberLinkWithFiltereredMessages> GetMasterLinks(int p_MemberID)
{
    return Get()
        .Include(memberLink => memberLink.MasterMember)
        .Include(memberLink => memberLink.SlaveMember)
        .Where(memberLink => memberLink.MasterMember.RecordID == p_MemberID)
        .Select(memberLink => new MemberLinkWithFilteredMessages
        {
            MemberLink = memberLink,
            FilteredMessages = memberLink.MasterMember.ReceivedMessages
                .Where(msg => msg.Sender.RecordID == memberLink.SlaveMember.RecordID)
        })
        .ToList();
}

您真正在做的是询问特定的信息子集,因此请明确说明。

于 2013-09-10T02:12:48.957 回答