简体   繁体   中英

Navigation properties to the same table

I have the folling model in my project (EF5, DBContext, database first):

Customer

 InvoiceAddress -> Addresses (table)
 DeliveryAddress -> Addresses (table)

So I'm having 2 foreign keys to the same table.

When I load the customer entity using the following statement:

 var cst = ctx.Customers.Where(c => c.CustomerID == 2).SingleOrDefault();
     ctx.Entry(cst).Reference(c => c.InvoiceAddress).Load();

After the reference of the InvoiceAddress is loaded, the DeliveryAddress is also loaded. However this only happends when the invoice and delivery ID are the same. When they are not equal, the DeliveryAddress is not loaded. What is causing this behavior?

Here's an educated guess:

When you eagerly reference an entity, you're SELECT ing it immediately. When you get your data, entity manager creates the entities in EF sense. Since the DeliveryAddress and InvoiceAddress are effectively the same entity (same PK, if you had a composite key, it would have to be the same composite key), it uses the same instance to represent both of them, which also means that the both addresses get loaded - because why not? It's exactly the same entity, the data is pointing to the same row in the DB. References are shared and it uses less memory.

If the PKs are different, then the invoice and delivery addresses are represented by different entities, loading one won't affect the other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM