Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my EF4.1 relationship not get set to null upon assignment of a null value?

In my system I have tasks, which can optionally be assigned to contacts. So in my business logic I have the following code:

 if (_contactChanged) { task.Contact = contact; }

If no contact was specified, the contact variable is null. This is supposed to null out the contact relationship when I submit changes, however I have noticed this isn't happening 99% of the time I do it (I have seen it happen once, but not consistently after stepping through this code over and over).

When I debug, I have verified that _contactChanged is true and the inside code isn't getting hit. However, after I step past task.Contact = contact; I notice that while contact is null, task.Contact is of type

{System.Data.Entity.DynamicProxies
.Contact_4DF70AA1AA8A6A94E9377F65D7B1DD3A837851FD3442862716FA7E966FFCBAB9}

and still has the previous data tied to it.

Why is the proxy not being set to null, and how can I get this to work properly?

like image 934
KallDrexx Avatar asked Apr 23 '11 14:04

KallDrexx


1 Answers

Wow. Great question. I was able to confirm/reproduce this, even if the referent is not a dynamic proxy. t.Contact = null; doesn't work!

The best answer I have so far is to say:

    context.Entry(task).Reference(t => t.Contact).CurrentValue = null;

I'm really hoping that there is a better way than this, because this is some pretty inconvenient syntax.

UPDATE:

This works:

    var task = context.Tasks
        .Where(...your condition here...)
        .Include(t => t.Contact)
        .First();

    task.Contact = null;

OR,

If you have a foreign key ID defined in your model (as in a nullable ContactId), this becomes a lot easier.

like image 111
anon Avatar answered Oct 13 '22 02:10

anon