Entity Framework .Where nested in .Include

前端 未结 1 2010
醉梦人生
醉梦人生 2020-11-30 14:48

I\'m attempting to perform a db lookup using EF5 code-first. The basic structure and table relationships are as follows;

public partial class Member
{
    pu         


        
相关标签:
1条回答
  • 2020-11-30 15:48

    The short answer is no, EF will not let you do that using Include().

    Think about the result if it let you do this: in one case your MemberLink.MasterMember.ReceivedMessages will be fully populated, on another identical looking object MemberLink.MasterMember.ReceivedMessages is actually a sub-set of messages! What happens if you try to add to the ReceivedMessages? What if the addition doesn't match the filter? It is a bag of hurt.

    The answer is to use projections:

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

    What you are really doing is asking for a specific sub-set of information, so be explicit about it.

    0 讨论(0)
提交回复
热议问题