Merijn
Merijn

Reputation: 723

EntityFramework: possible many-2-many bug in EF 5.0?

I've a simple DbContext model with two entities Product and Order, and a single many-2-many association between them. I'm trying to explicitly load a specific associated order for a product instance. Therefore, I started with explicitly loading all orders for the product instance:

context.Entry(product).Collection(x=>x.Orders).Load();

product.Orders now contains all associated orders. So far so good. Now I want to make a more specific query by using the '.Query()' method like this:

context.Entry(product).Collection(x=>x.Orders).Query().Load();

Surprisingly, product.Orders is now empty!

According to the documentation, the Query() method should return 'the query that would be used to load this collection from the database.' Executing the ObjectQuery manually does give the expected result.

Am I doing something wrong, or is this a bug in EF?

Thanks in advance for your help.

Kind regards, Merijn

Upvotes: 1

Views: 123

Answers (1)

Gert Arnold
Gert Arnold

Reputation: 109185

The difference is that the second statement (with Query().Load()) only loads the orders into the context, not in the collection. It's just a query that runs, it is not aware of any collection it should populate.

You can verify that by listing context.Orders.Local. After the Query().Load() it will contain the orders belonging to product.

If product.Orders would be allowed to lazy load afterwards you would see the same query being executed, but now to populate the collection.

Edit
After clearing my head and keeping apart many-to-many, one-to-many, lazy/non-lazy I could fully reproduce your issue. A m:m navigation property is not loaded by .Query().Load(), whereas a 1:n navigation property is. The Local collection is loaded in both cases, though.

So, good catch!

Upvotes: 1

Related Questions