views:

22

answers:

1

Here is my simplest structure

Customer
   CustomerID
   FirstName
   LastName
   ...
   BrokerID <- Navigation Property created with this FK

Broker
   BrokerID
   FirstName
   LastName

Now my question is, if I load multiple customers, and I want to see list of customer and I also need to see the Name of Broker associated with the customer, now one broker will probably have many customers, so multilple customers returned will most likely have repeated BrokerIDs.

I guess by default EF will return new instance of Broker for every customer and it will query load broker for every broker even if it is repeated.

Is there anyway I can make EF not load broker if the same broker was loaded before? Does this kind of caching (only for small sessoin) exist in EF or I have to add my own implementation of Navigation Properties?

+1  A: 

Unless you have some example where it really happens, for first part of your question I believe you are wrong. EF will not create new instance for already loaded broker. EF as any other ORM tool uses IdentityMap pattern which handles that each loaded object exists only in single instance.

Second part of your question is more difficult because it is related to query executed on database. I didn't check this with EF but in Linq-To-Sql query differed based on number of navigation properties loaded with main object. If you loaded just single navigation property it usually executed simple join so the records were duplicated. But in case of multiple navigation properites query was divided into multiple queries loading data from separate tables. So this behavior was somehow optimized by default.

Ladislav Mrnka
IdentityMap is interesting, I didnt know about that, but I guess that is even subjected to concurrency issue, if two customer has a same broker, the navigation property has a same broker object instance? loaded in one query?
Akash Kava
I don't see any concurrency issue. IdentityMap is handled per object context. Object context is usually not shared. If single thread requests multiple customers which share single broker it is natural that broker is represented by single instance shared among customers.
Ladislav Mrnka