views:

86

answers:

2

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)

A: 

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

Andrey
e.InvitedUser is not nullable. There is no exception text except for NullReferenceException and "object not set to an instance...", when trying to access any of the mentioned paths.
Mickel
i would tell what is text for NRE if i was woken in middle of night. Please give as much MEANINGFUL details as possible. stack trace is one of them. it gives you even line number where error happened.
Andrey
+3  A: 

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

Nix
InvitingUser/InvitedUser are just Navigation Properties, these cannot be set as Nullable in EF.
Mickel
They are NAV properties that are tied to a FK, read the article or just create a test project, when you call DeleteObject it will null any FK it can.
Nix
I think he means "of 0..* or 0..1 cardinality", which is not quite the same meaning as "nullable," but you get the idea... @Nix is right, BTW. Relationships are themselves first-class entities in the EF. If you delete an object, the relationship goes, too, as it must. Remember there's another object on the other end. That object can't have a relationship to a deleted object.
Craig Stuntz
Yes, 0..*. Thx for your help. Isn't there any way to just detach all objects in one of the lists and return that and delete them from the other list?
Mickel