0
votes

I've got lazy loading off, and proxy creation doesn't matter (tried both true and false, no difference).

I have this model:

public class Comment{

    [Required]
    public int SenderID { get; set; }

    public User Sender { get; set; }

}

(and of course, I have a user class).

At database level, I confirm that the Sender is a valid User object. I have some IQueryable<Comment> named commentsQuery (that basically takes some comments from a post. Then I include the Sender navigation property and execute the query:

var comments = commentsQuery.Take(50).OrderBy(c => c.ID).Include(c => c.Sender).ToList();

However, some comment objects inside the list have their Sender set to null even though I've explicitly included the navigation property.

If I turn on lazy loading it works correctly, but I don't want to turn on lazy loading.

Why is the explicitly-included required navigation property null? (I'm on Entity Framework 6.1.3)

1

1 Answers

0
votes

Okay, just figured out myself. I had to include the sender at the original query when I'm constructing it from the database context.

I was using:

 var post = await Database.Posts.Where(p => p.ID == postId && p.Sender.Username == username).Include(p => p.Sender).Include(p => p.Comments).FirstOrDefaultAsync();
 IQueryable<Comment> commentsQuery = post.Comments.ActiveObjects().OrderByDescending(c => c.ID).AsQueryable();

And then, I assume Entity Framework was just ignoring (I think it's a design issue at Microsoft's side) the later-included navigation property (commentsQuery.[...].Include(c => c.Sender)).

I've modified the original query to include the second-level navigation property:

var post = await Database.Posts.Where(p => p.ID == postId && p.Sender.Username == username).Include(p => p.Sender).Include(p => p.Comments).Include(p => p.Comments.Select(c => c.Sender)).FirstOrDefaultAsync();

(notice the addition of .Include(p => p.Comments.Select(c => c.Sender))

Now, my query works properly. I'm not sure if it's the best way to do it though, anyway, it's not the scope of this question.