I am making a website on asp.net MVC and I am using a repository interface to use repository in memory and using database.
I have all my relationships fixed up, what I mean is for example when I have one contact than he have addresses, so.. when I add one address to this contact automatically fixup the relashionship for address.contact points to the contact, and I leave the properties virtual for entity framework create the proxies then using database repository.
My question starts here:
I have one query like this:
return query.Where(c => c.UserID == clientId)
.Include(c => c.AssignedProjects)
.Select(c => new UserDetailsData<Client>
{
User = c,
IssuesCount = c.IssuesReported.Count()
}).Single();
that uses include.
If I remove the Select assignedProjects will contain the Projects for this client, but when I include Select AssignedProjects is null and anonymous object is fine but.. user don’t contain any AssignedProjects.
In memory I can do that, but using EF I cannot.
The final graph that I want is.. The user with clientID having collection AssignedProjects with his projects and creates anonymous object with User (with the collection) and IssuesCount passing to a view to show the AssignedProjects, The User information and the number of issues that client reported..
Anyone know how I can resolve this?
You can try this:
Although you are not really interested in the
AssignedProjectsproperty of the type you project into it will populate theUser.AssignedProjectsproperty too. This leverages “relationship span”, a feature in EF which automatically builds up navigation properties of objects loaded into the context.Be aware that this really relies on the fact that you load the objects into the context. If you disable tracking – for instance by using
AsNoTracking()in your query – it doesn’t work anymore.