NullReferenceException in EntityFramework, how come?

痴心易碎 提交于 2019-12-25 02:53:58

问题


Take a look at this query:

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.

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.

How come?

[EDIT] 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)


回答1:


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

(0-1)FK-> InvitingUser

(0-1)FK-> InvitedUser

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

Deleting Objects




回答2:


please, post exception texts. e.InvitedUser is it nullable? this piece looks suspicious: e.InvitedUser.UserId



来源:https://stackoverflow.com/questions/2682722/nullreferenceexception-in-entityframework-how-come

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!