Question

I am using Entity Framework CodeFirst where I have used Parent Child relations using ICollection as

public class Person
{
   public string UserName { get;set}
   public ICollection<Blog> Blogs { get; set;}
}

public class Blog
{
   public int id { get; set; }
   public string Subject { get; set; }
   public string Body { get; set; }
}

Ok, so far everything is working ok, but my concern is, whenever I want to get the Blogs of a person, I get it as

var thePerson = _context.Persons.Where(x => x.UserName = 'xxx').SingleOrDefault();
var theBlogs = thePerson.Blogs.OrderBy(id).Take(5);

Now, I understand that, when the line is executed, all Blogs for that person is loaded into the memory and then sorting and selecting is done from memory. That is not ideal for a record of Person who has large number of blogs. I want to make the Blog Child as IQueryable so that the Sorting and Selecting is done in SQL database before pulling to Memory.

I know I could declare the Blogs as IQueryable in my context so that I could directly query as

var theBlogs = _context.Blogs.Where(.....)

but that is not feasible for me due to design choice, I want to avoid any circular reference as much as possible due to serialization problem. So, I did not make any reference of the parent entity in my child.

I found that, i can call AsQueryable() method on the blogs as

var theBlogs = thePerson.Blogs.AsQueryable().OrderBy(id).Take(5);

That looks like a magic for me and seems too good to be true. So my question. Does this AsQueryable really make the ICollection as IQueryable in reality and makes all Query process in SQL Server (Lazy loading) OR it is just a casting where Blogs are loaded into memory as like before, but change the interface from ICollection to IQueryable ?

Was it helpful?

Solution

So actually it appears that writing your navigation property as IQueryable<T> is not possible.

What you could do is adding a navigation property to Blog:

public class Blog
{
   public int id { get; set; }
   public string Subject { get; set; }
   public string Body { get; set; }
   public virtual Person Owner { get; set; }
}

From that, you can query as follows so it won't load everything into memory:

var thePerson = _context.Persons.Where(x => x.UserName = 'xxx').SingleOrDefault();
var results = _context.Blogs.Where(z => z.Person.Name = thePerson.Name).OrderBy(id).Take(5)

I suggest you to try LINQPad to see how LINQ is translated into SQL, and what is actually requested from the DB.

OTHER TIPS

A better approach is described in Ladislav's answer. In your case:

var theBlogs = _context.Entry(thePerson)
                       .Collection(x => x.Blogs)
                       .Query()
                       .OrderBy(x => x.id)
                       .Take(5);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top