Merge two collection of the entities?
Sometimes in our applications we have problems with the performance of the operations, that are performed on the collections of the entities. Usually the problem is caused by a lot of joins between tables. If we don't want to build big, time consuming queries that return a lot of data, we can hit database a few more times and join the returned collections.
In this case, when we can get some objects in one hit (using Entity Framework) and after that, take the children (objects connected with the navigation properties) using another query. After that we can merge both collections by setting the correct values of the navigation properties in any of those two collections.
Faster solution
However, if we do both of operations using one ObjectContext in one scope, we do not need to set the navigation properties manually. The Entity Framework will do this for us automatically.
In the example below we pass the collection of the entities without connected navigation properties to the method, then we get the id's (or any other identification fields from the entities) and we take the data from the included table with full product data. In this case we do not need to merge the collections. As a result of this method we will receive the collection of ProductSets with attached products with all the full data included.
Example
public static void AttachDespatchItemsToDespatchPackages(List<ProductSet> listToWhichWeWantToAttachObjects, ObjectContext ctx) { List<int> productsSetsIds = listToWhichWeWantToAttachObjects .SelectMany(d => d.ProductSets.Select(dp => dp.ProductSetId)) .Distinct() .ToList(); List<Product> productsForProductSet = new List<Product>(); if (productsSetsIds.Any()) { productsForProductSet = ctx.Products .Include("FullProductData") .Where(p => productsSetsIds.Contains(p.ProductSetId)) .ToList(); } }