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 开发者_StackOverflow中文版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)
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
please, post exception texts. e.InvitedUser
is it nullable? this piece looks suspicious: e.InvitedUser.UserId
精彩评论