Why is my EF4.1 link not getting null when assigning a null value?

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

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

If no contact is specified, the contact variable is null. It is assumed that I reject the contact relationship when I submit the changes, but I noticed that this does not happen in 99% of the times when I do this (I saw it happen once, but not sequentially after repeatedly passing this code).

When I debug, I confirmed that _contactChanged is true and the internal code does not hit. However, after I walked past task.Contact = contact; I noticed that while contact is null, task.Contact is of type

 {System.Data.Entity.DynamicProxies .Contact_4DF70AA1AA8A6A94E9377F65D7B1DD3A837851FD3442862716FA7E966FFCBAB9} 

and still tied to previous data.

Why is the proxy not set to null and how can I make it work correctly?

+6
source share
1 answer

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

The best answer I have so far is to say:

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

I really hope that there is a better way than this, because it is a rather inconvenient syntax.

UPDATE:

It works:

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

OR,

If you have a foreign key identifier defined in your model (as in a NULL contact), this becomes much easier.

+9
source

Source: https://habr.com/ru/post/886534/


All Articles