Search code examples
entity-frameworkormef-code-firsteager-loadingef-database-first

Move From Entity Framework Database First to Code First gives problems for ObjectQuery and will Not Eager Load properly


Our company has a software application that uses

-Entity Framework 4

-Code First approach

The application used to be based on Entity Framework Database First code, however, we changed it to start using the Code First approach.

We have some problems that are similar to one's mentioned in Alex D James blog post here: https://blogs.msdn.microsoft.com/alexj/2009/06/02/tip-22-how-to-make-include-really-include/

Our old code that was based on Entity Framework Database First code used to have code like the following:

 var results =
         ((from post in ctx.Posts
         from blog in post.Blogs
         where blog.Owner.EmailAddress == “alexj@microsoft.com”
         select post) as ObjectQuery<Post>).Include(“Comments”);

However, since we changed to the Code First approach, the aforementioned post will give the following error:

Object reference not set to an instance of an object.

It seems to be some kind of problem that arose when we moved from Entity Framework Database First code to Code First

We modified the code to look like the following:

var results =
        (from post in ctx.Posts.Include(“Comments”)
        from blog in post.Blogs
        where blog.Owner.EmailAddress == “alexj@microsoft.com”
        select post);

However, the Post entities associated Comments (i.e. a Navigation property of Collection of Comments) will Not be "Eager Loaded" which is problematic because till will throw the following error:

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

Could someone please tell me how we can modify the code so that it works properly for Entity Framework Code First approach?


Solution

  • Reference: How can i convert a DBQuery<T> to an ObjectQuery<T>?

    @ladislav-mrnka states: "

    DbQuery contains Include method so you don't need to convert to ObjectQuery. ObjectQuery is not accessible from DbQuery instance - it is wrapped in internal type InternalQuery and conversion operator is not defined.

    Btw. when you add using System.Data.Entity and refrence CTP5 you will be able to call Include on IQueryable! "