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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With