How can I perform an integration tests to test for eager loaded entities (EF4 Code First)
Here is a simple scenario to explain what I am trying to do. Say I am creating a Blogging engine, and I have 2 entities, Post
and Comment
, with a 1-to-many relationship between the two. In my service layer, I have a query logic to retrieve the details about a post that goes like:
Post post = new PostByIdQuery(_unitOfWork).WithPostI开发者_如何学Cd(5).Execute();
That line of code will execute a query that will retrieve the post entity from the database with an id value of 5. This query object is already coded and passes integration tests using a real database.
There are two business processes in which I may want to get a post by a specified ID, if I am editing a post or when I am displaying a post with its comments. This query object works fine for both scenarios, but there are performance implications when displaying a post with it's comments since the comment list is by default lazy loaded. Thus while iterating through the comments for a post will cause multiple database hits.
Of course, if I always eager load the comments for a post, if I"m just editing a post it causes unnecessary table joins.
Thus I want to add a new method to the fluent interface that will specifies if comments should be lazy loaded or not. The question is, how do I write an integration test that checks if the comment table is eager loaded or not so this new requirement can be checked whenever unit/integration tests are run?
As far as I can tell, the Post.Comments
property will show the same when accessed whether it's eager loaded or lazy loaded, so I'm not sure how to create a test for this.
Edit: As an FYI, this is using the Code-First mechanism of EF4, thus my entities are POCOs.
There's a chance you'll be able to cast the collection object to the more advanced EntityCollection type, and then check the IsLoaded property therein.
Assert.IsTrue(((EntityCollection<Comment>)Post.Comments).IsLoaded);
If that doesn't work, have a look at Rowan's answer to this question I asked a while ago. I was trying to get my code-first collection to be exposed as EntityCollection for a different reason.
Using CreateSourceQuery in CTP4 Code First
精彩评论