为什么我的EF4.1关系不会被置在一个空值赋值为null? [英] 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; }
如果没有指定联系人,在联系人
变量为空。这是的应该的以空出的接触关系时,我提交的变化,但是我已经注意到这是不会发生的我做了99%的时候(我已经看到它发生一次,但毕竟不能始终如一通过这个代码,一遍又一遍)步进。
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).
当我调试,我已经验证了 _contactChanged
是真正
和里面的代码是不是击中。然而,当我踩过去 task.Contact =接触;
我注意到,虽然联系人
为空, task.Contact
的类型
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.
为什么代理没有被设置为null,我怎么能得到这个正常工作?
Why is the proxy not being set to null, and how can I get this to work properly?
推荐答案
哇。问得好。我能够证实/重现此,即使指涉不是动态代理。 t.Contact = NULL;
不起作用
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.
更新:
本作品:
var task = context.Tasks
.Where(...your condition here...)
.Include(t => t.Contact)
.First();
task.Contact = null;
或
如果你有一个(如在一个可为空的ContactID)在模型中定义的外键ID,这个就简单多了。
If you have a foreign key ID defined in your model (as in a nullable ContactId), this becomes a lot easier.
这篇关于为什么我的EF4.1关系不会被置在一个空值赋值为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!