Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

entity framework - If I select from an IQueryable then the Include is lost

The include does not work after I perform a select on the IQueryable query. Is there a way around this? My query is

public IQueryable<Network> GetAllNetworks()
{
    var query = (from n in _db.NetworkSet
                .Include("NetworkContacts.Contact")
                .Include("NetworkContacts.Contact.RelationshipSource.Target")
                .Include("NetworkContacts.Contact.RelationshipSource.Source")
                 select (n));        
    return query;;
}

I then try to populate my ViewModel in my WebUI layer using the following code

            var projectedNetworks =
            from n in GetAllNetworks()
            select new NetworkViewModel
            {
                Name = n.Name,
                Contacts = from contact in networkList
                    .SelectMany(nc => nc.NetworkContacts)
                    .Where(nc => nc.Member == true)
                    .Where(nc => nc.NetworkId == n.ID)
                    .Select(c => c.Contact)                        
                    select contact,
            };

        return projectedNetworks;

The problem now occurs in my newly created NetworkViewModel; the Contacts collection objects do not include any loaded data for RelationshipSource.Target or RelationshipSource.Source.

However the data is there when run from the original Repository IQueryable method. However the related include data does not seem to get transferred into the new Contacts collection that is created when I use the Select New NetworkViewModel {}.

Is there a way to preserve this Include data when it gets passed into a new object? At the moment I just keep getting Null exceptions

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here's an explanation of what's happening, with a workaround.

In your case, however, I think there's a better workaround than what's in that linked article. You're already using a view model for Network. That's good! Do it for contact (and it's related properties), too, and your problems with eager loading will magically go away. Projection always works.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...