Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lazy loading not working when on new saved objects, (when getting them from the context that saved them)

I have this class

public class Comment
{      
    public long Id { get; set; }
    public string Body { get; set; }
    public long OwnerId { get; set; }
    public virtual Account Owner { get; set; }
    public DateTime CreationDate { get; set; }
}

the problem is that the virtual property owner is that I get null object reference exception when doing:

comment.Owner.Name

when calling this right after the object was saved (from the same instance of DbContext) with a new context will work

anybody knows anything about this?

like image 203
Omu Avatar asked Sep 23 '11 19:09

Omu


1 Answers

That is because you created Comment with constructor. That means that Comment instance is not proxied and it cannot use lazy loading. You must use Create method on DbSet instead to get proxied instance of Comment:

var comment = context.Comments.Create();
// fill comment
context.Comments.Add(comment);
context.SaveChanges();
string name = comment.Owner.Name; // Now it should work because comment instance is proxied
like image 194
Ladislav Mrnka Avatar answered Oct 21 '22 00:10

Ladislav Mrnka