Phsycic Debugging from Blogs

time to read 3 min | 524 words

Well, I got my phsycic hat today, and I wanted to refer to Frans' post and try to answer the question that Frans is asking:

Roger:

9. Provide read-only access to foreign key values.

Mike:

This is actually a feature I’m fighting to get into our final milestone for V1. Can you describe the scenarios where this is used? Do you need the ability to query on the foreign key value, or simply expose it on the domain object?

If I have an Order entity object in memory, if I want to obtain its CustomerID and I only have the ability to get that ID is by fetching the related Customer entity into memory, instead of doing Order.CustomerID, I lose performance which is unnecessary. It's simple data-access stuff and it puzzles me a bit why Mike has to put up a fight to get this into their framework in the first place. Especially since the underlying object context knows that Order.CustomerID as it has to save it to the DB if you change the Customer related to that particular Order instance.

I should mention that I know very little about the way the Entity Framework internals work, but I would like to make an educated guess about the reasons for this issue, and why it is appernatly hard to do for V1.

The problem is basically this:

Order order = GetOrderFromDatabase();
Console.WriteLine("Order's Customer ID: {0}", order.Customer.CustomerID);

Now, the Entity Framework is apperantely not able to handle this case without loading the entire customer entity, which isn't really not needed, since you already have loaded the CustomerID column when you loaded the Order entity.

The reason that this is likely hard (again, I am making guesses here) is that the EF uses code generation where other frameworks use interception, and I assume that there isn't really a good way to detect when the identifier property is access and when it is a normal property (that does require loading the object). This likely means that trying to access the Customer entity when it is not loaded would throw, and trying to deal with that would force the EF to handle lazy loading, which is something that they seem to want to push to the client, rather than the framework.