1

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?

hs.chandra
  • 707
  • 1
  • 7
  • 19
NRonald
  • 13
  • 3

1 Answers1

1

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.

Patryk Ćwiek
  • 14,078
  • 3
  • 55
  • 76
  • What you are sugest make sens. However, i defined two different foreign keys in the database, and there are also two keys in the entity model. When I try to change the value of the delivery address, then this result in a 'A referential integrity constraint violation occurred' – NRonald Apr 05 '13 at 10:16
  • @NRonald Keys are separate, but in the end they point to the same data. The exception you listed is explained [here](http://stackoverflow.com/a/11596430/1180426) and [here](http://stackoverflow.com/a/12977804/1180426), without further details it's hard to really know what's happening... – Patryk Ćwiek Apr 05 '13 at 10:21
  • Is it possible to create '2 different' endpoints? The only solution I see now is to set all navigation properties to null before the Save(). – NRonald Apr 05 '13 at 11:07
  • @NRonald If you want to change the whole address, e.g. `DeliveryAddress`, it probably would be the easiest to change the foreign key and let the entity update itself, other than that - setting nav properties to null is an option too. – Patryk Ćwiek Apr 05 '13 at 11:10