1

If we manually build our associations will we have to expose foreign keys in our domain model?

For example, if I a retrieve all Products and all Categories, the only way I can manually build the Product.Categories property is if I expose the ProductCategory mapping in my model?

I'd rather not do this if there is an alternative (note that eager loading via EF is not an option as I have two many associations to load).

Ben Foster
  • 34,340
  • 40
  • 176
  • 285
  • How do you intend to expose the associations? – Phil C Feb 23 '11 at 17:53
  • The associations are still present, they would just not be loaded by EF. By default it's not necessary to expose the mapping table, but I think it may be necessary if I was to load the association manually. – Ben Foster Feb 23 '11 at 22:00

2 Answers2

0

You could add a partial class "Product" to your project and extend your "Product" entity with an IEnumerable<Category> property "Categories" (Or even a method that returns IEnumerable<Category>).

This way you could implement the retrieval of "Categories" yourself.

SolarX
  • 1,873
  • 2
  • 18
  • 26
  • I do not need to do this. Product already has a Categories property. My point (and question) is whether it is necessary to expose foreign keys / mapping tables in my domain model in order to load the association properties manually, and I think the answer is probably yes. – Ben Foster Feb 23 '11 at 22:01
0

The solution was to use a Linq projection to retrieve the relevant keys.

var tags = (from p in postRepo.GetAll()
        from t in p.Tags
        select new
        {
            PostId = p.Id,
            Tag = t
        }).Take(1000).ToList();

I stick the results of the above query into a List<KeyValuePair<Guid, Tag>> which is then cached. When I load a Post I can manually build it's "Tags" collection from the cache.

This is an approach that we have had to take with a number of associations now. Whilst lazy loading is very convenient, IMHO it should not be used with your Views.

By caching common associations using the above method, we were able to reduce a page previously issuing 59 queries (as a result of lazy loading) to just 6 queries.

Ben Foster
  • 34,340
  • 40
  • 176
  • 285