EF4: Syncing Foreign Keys and EntityReference.EntityKey

In EF version 1, a reference entity and it’s related EntityReference.EntityKey stay in sync when you change one or the other.

E.g., if you have a sales order, it’s Customer property and the CustomerReference.EntityKey are automatically kept in sync by the ObjectContext.

(Thanks to Craig for poiting out in the comments that I need to clarify an assumption here...the assumptoin is that the Customer entity exists in memory. If it's  not in memory than there is nothing to sync with. )

What happens as we introduce foreign key values into the model? Now we have three pieces of information to synchronize.

Here’s an experiment I did to check what happens.

1. Create a new entity in memory and assign some foreign key properties

 var res=new Reservation();
 res.TripID=34;
 res.ContactID=12;
 res.ReservationDate=DateTime.Now;

2. Add the entity to the context

 context.Reservations.AddObject(res);

3. Then look to see if the EntityReference.EntityKeys were automatically created, and yes they were.

image

 

4. Next I changed the foreign key value

  res.TripID = 7; 

5. and checked the reference key again.

image

Again, they were in sync.

6. Changing the EntityKey itself

res.TripReference.EntityKey = 
  new System.Data.EntityKey("BAEntities.Trips", "TripID", 34);

continues to keep the foreign key property in sync.

image

7. Finally, I queried for an existing trip entity and set my reservation’s Trip navigation property to this trip.

 var trip = context.Trips.First();
res.Trip = trip;

The TripID of this newly retrieved trip is “1”.

And I can see that the foreign key property and EntityReference.EntityKey continue to stay in sync with this.

image

image

#1 Craig Stuntz on 10.20.2009 at 12:43 PM

> In EF version 1, a reference entity and it’s related

> EntityReference.EntityKey stay in sync when you change one or the other.

Not necessarily. If you assign the EntityKey and the related object isn't in the context, it won't be loaded or referenceable. Makes sense, but they can get out of sync.

I'm enjoying your series on EF 4; please keep them up!

Leave a Comment