EF3.5 and relationships


Having been using EF3.5 lately, I just thought I’d point of one of the things that they did which – to my mind – was completely mad (thankfully rectified in EF4).

  1. You have a parent-child relationship e.g. Course and Pupil
  2. You load a Pupil instance on its own
  3. You want to find out the ID of the Course that this Pupil belongs to i.e. the foreign key.
  4. You are in an n-tier, or otherwise disconnected environment, or one where performance is a key factor.

In EF3.5, there is no easy, strongly-typed way of doing this, without a further round trip back to the data source in order to load the parent Course, and then navigate to that object e.g.

Pupil pupil = LoadPupil("Isaac");
if (!pupil.CourseReference.IsLoaded)
    pupil.CourseReference.Load();
int courseId = pupil.Course.Id;

Of course, in a perfect world, you have a superfast database with lots of memory etc. etc. so this approach works fine, in theory.

In the real world, it’s not that good when you need something high performing, with minimal unnecessary round trips to the DB. You could argue that I should simply Include() the Course when loading the Pupil – yep, that’d work – but again, why should I need to load the entire entity in just to get that one field? Why should I have to do a join or union in SQL just for that one field when the Pupil should already be able to provide this information to me?

Thankfully, in EF4 you can expose the FK fields so that you can get to them as e.g. Pupil.CourseId. I can sort of see why someone might not want them in the conceptual model, but compare that with how you have to do it in EF3.5:

Pupil pupil = LoadPupil("Isaac");
int courseId;
if (!pupil.CourseReference.IsLoaded)
    courseId = (int)pupil.CourseReference.EntityKey.EntityKeyValues[0].Value;
else
    courseId = pupil.Course.Id;

That’s right – an array of key/value pairs which represent the key between Pupil and Course. Naturally, the key/value pair is weakly typed, so you have to cast the id back to an int. Another developer without a decent amount of EF experience will not be able to look at this code and automatically know what is going on; you’d need to comment it or similar to explain the intent.

Anyway – rant over. It just annoyed me today that this was the best solution that they came up with for EF3.5.

Coming up: Entity Framework and inheritance!

Advertisements

2 thoughts on “EF3.5 and relationships

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s