本文介绍了EntityFramework中的NullReferenceException,怎么来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看看这个查询:

var user = GetUser(userId);
var sessionInvites = ctx.SessionInvites
    .Include("InvitingUser")
    .Include("InvitedUser")
    .Where(e => e.InvitedUser.UserId == user.UserId)
    .ToList();

var invites = sessionInvites;

// Commenting out the two lines below, and it works as expected.
foreach (var invite in sessionInvites)
    ctx.DeleteObject(invite);

ctx.SaveChanges();

return invites;

现在,这里的所有内容都可以正确执行.已删除该用户的邀请,并且成功返回邀请.

Now, everything here executes without any errors. The invites that exists for the user are being deleted and the invites are being returned with success.

但是,当我然后尝试在任何返回的邀请上导航到InvitingUserInvitedUser时,我得到了NullReferenceException.返回的SessionIvites的所有其他属性都可以正常工作.

However, when I then try to navigate to either InvitingUser or InvitedUser on any of the returned invites, I get NullReferenceException. All other properties of the SessionIvites returned, works fine.

怎么来?

现在,很奇怪的是,如果我用Delete注释掉这些行,它会按预期工作. (除了实体不会被删除:S)

Now the weird thing is, if I comment out the lines with delete it works as expected. (Except that the entities will not get deleted :S)

推荐答案

DeleteObject()的副作用之一是EF将使所有可为空的FK无效,结果您所有的关联(InvitingUser/InvitedUser)都消失了

One of the side affects of DeleteObject() is EF will null any FK that is nullable, as a result all of your associations(InvitingUser/InvitedUser) are gone.

我的假设是您的结构是这样(基数)

My assumption is that your structure is like this (Cardinality)

SessionInvites

SessionInvites

(0-1)FK->邀请用户

(0-1)FK-> InvitingUser

(0-1)FK-> InvitedUser

(0-1)FK-> InvitedUser

结果.当您调用DeleteObject时,EF会将导航属性设置为InvitingUser/InvitedUser

As a result. When you call DeleteObject EF will null your naivigation properties to InvitingUser/InvitedUser

删除对象

这篇关于EntityFramework中的NullReferenceException,怎么来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 17:11