I’m having difficulty with ObjectContext.LoadProperty (EF 4 Database First) (both the string and expression overloads exhibit the same behavior for me). Given the following simple schema:
Product
--------------
ProductId (pk)
...
Order
--------------
OrderId (pk)
...
OrderItem
--------------
OrderId (pk, fk Order),
ItemNumber (pk),
ProductId (fk Product)
...
Because I’ve found it to perform better than Includes in my particular scenario, I’m using LoadProperty to populate the related entity. For example,
Order ord = context.Orders.Where(o => o.OrderId = 1).FirstOrDefault();
context.LoadProperty(ord, o => o.Items); // Items is the navigation property name for the
OrderItem -> Order relationship
foreach(var i in ord.Items)
{
context.LoadProperty(i, oi => oi.Product);
}
This has been in place for some time and has worked (as you’d expect) just fine. However, this morning we started encountering a scenario where even after calling LoadProperty, i.Product was still null. i.ProductId is valid and I can even load the product explicitly like so:
var product = context.Products.Where(p => p.ProductId == i.ProductId).FirstOrDefault();
But LoadProperty won’t load the object. No exception is thrown, it just simply doesn’t load it. I’ve also tried specifying MergeOptions.OverwriteChanges (even though there aren’t any), and the results have been predictably the same.
What could cause ObjectContext.LoadProperty to fail silently in this manner?
I’ve discovered that this appears to be an issue (if not an outright bug) with the way EF’s
LoadPropertyfunction works.The
OrderItemandProducttables had values forProductIdthat differed either by case, trailing spaces, or both. Given SQL Server’s default collation, this was legal and referential integrity was maintained. This is why queries for the product worked, but it seems that EF was doing key comparisons internally somewhere and being more stringent about these values.If you encounter this issue yourself, you can check for trailing spaces by using the T-SQL
DATALENGTHfunction in your query and you can compare case by using a different collation.For example, you can see discrepancies in my above model using this:
Note that it may be possible to compare both trailing spaces and character casing using collation only; if anyone knows the name of a collation that does such a thing, feel free to edit this answer or post a comment and I’ll update. Until then, this should do what’s necessary.