开发者

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 nu开发者_JAVA技巧ll 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜