Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy Loading with DbContext

I have this:

Post post = GetPost(postID);

if (post.User.UserID == userID)
    return true;

And GetPost():

public Post GetPost(int postID)
{
    var ctx = new ForumContextContainer();
    var post = (from p in _ctx.PostSet
                where p.PostID == postID
                select p).FirstOrDefault();
    return post;
}

And Post itself:

public partial class Post
{
    public int PostID { get; set; }
    public string Text { get; set; }
    public System.DateTime Created { get; set; }
    public Nullable<int> Like { get; set; }
    public Nullable<int> Dislike { get; set; }

    public User User { get; set; }
    public Thread Thread { get; set; }
    public ICollection<Attachment> Attachment { get; set; }
    public ICollection<Reported> Reported { get; set; }
    public ICollection<Tag> Tag { get; set; }
}

Now As you may guess I want to compare if user created post or not. Problem is that User here is null. And my question is, do I have to load user explicitly, each time I call GetPost() or I can do it another way.

Asking because, let's say doing this every time thread is loaded for every post in thread, for every user browsing thread.. Well, you can see the math.

like image 707
Łukasz Baran Avatar asked Feb 25 '23 05:02

Łukasz Baran


1 Answers

If you make your navigation properties virtual and you will keep your context alive for the whole duration of the processing the EF will load the navigation property first time you access it - that is the lazy loading. If you don't make properties virtual or if you plan to close context in GetPost method (context is disposable!) you must explicitly load every navigation property you want to use by Include method.

like image 164
Ladislav Mrnka Avatar answered Mar 07 '23 09:03

Ladislav Mrnka