Lazy loading does not work when on new saved objects (when retrieving 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 owner of the virtual property is that I get a null object reference exception on execution:

 comment.Owner.Name 

when calling this right after saving the object (from the same DbContext instance) with the new context will work

Does anyone know about this?

+6
source share
1 answer

This is because you created the Comment constructor. This means that the Comment instance is not proxied and cannot use lazy loading. You should use the Create method on the DbSet instead to get a proxy 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 
+18
source

Source: https://habr.com/ru/post/897928/


All Articles