我刚才做了一些代码,首先用实体框架代码向我的表添加一个对象。
Context.Reactions.Attach(reaction);
Context.SaveChanges();
之后,我使用名为Profile的关系来获取发布反应的用户的名称。
reaction.Profile.FirstName + " " + reaction.Profile.LastName
现在过了一会儿,当我试图得到这个人的名字时,我在Profile上得到了一个null引用。
那么为什么我不能添加一个对象呢?之后使用Profile关系?
编辑: 我在Profile关系属性上得到了nullreference。所以反应.Profile说这是空的。这是同一个实例。实体框架给了我一个反应的id,所以savechanges()有效。 获取FirstName的行是直接在SaveChanges之后的行,因此上下文无法正确处理?
完整代码:
var reaction = new Reaction()
{
Text = reactionText,
ProfileId = CurrentProfileId,
PostedOn = DateTime.Now
};
//Save changes to the backend
context.Reactions.Add(reaction);
context.SaveChanges();
return Json(new
{
Id = reaction.Id,
ReactionType = reactionType,
ReactionTypeId = reactionTypeId,
ReactionText = reaction.Text,
PostedOn = reaction.PostedOn.ToString("G"),
ProfileName = string.Format("{0} {1}", reaction.Profile.FirstName, reaction.Profile.LastName)
});
我甚至尝试使用此代码。
using (var context = new SeeTingsContext())
{
context.Configuration.LazyLoadingEnabled = true;
}
答案 0 :(得分:0)
我在阅读after a while
时并没有得到你。这是否意味着您首先获得关系对象,然后突然变为空?
我的猜测是:
LazyLoadingEnabled
设置为true。 更新:根据评论,尝试明确加载关系,看看是否可以获取个人资料:
if (!context.Entry(reaction).Reference(r => r.Profile).IsLoaded)
{
context.Entry(reaction).Reference(r => r.Profile).Load();
}
如果您无法使用这种方式获取个人资料,我认为您的映射存在问题。