为什么在分配空值时我的 EF4.1 关系没有设置为空?
在我的系统中,我有任务,可以选择将其分配给联系人。因此,在我的业务逻辑中,我有以下代码:
if (_contactChanged) { task.Contact = contact; }
如果未指定联系人,则 contact
变量为 null。当我提交更改时,这应该使联系关系无效,但是我注意到99%的时间我都没有发生这种情况(我见过它发生一次,但之后并不一致一遍又一遍地单步执行此代码)。
当我调试时,我已验证 _contactChanged
为 true
并且内部代码没有受到攻击。但是,在我跳过 task.Contact = contact;
后,我注意到虽然 contact
为 null,但 task.Contact
是类型
{System.Data.Entity.DynamicProxies
.Contact_4DF70AA1AA8A6A94E9377F65D7B1DD3A837851FD3442862716FA7E966FFCBAB9}
并且仍然具有与其相关的先前数据。
为什么代理没有设置为 null,如何才能使其正常工作?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
哇。很好的问题。我能够确认/重现这一点,即使引用对象不是动态代理。
t.Contact = null;
不起作用!到目前为止我得到的最好答案是:
我真的希望有比这更好的方法,因为这是一些非常不方便的语法。
更新:
这有效:
或者,
如果您在模型中定义了外键 ID(如可以为 null 的 ContactId 中),则这会变得容易得多。
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:
I'm really hoping that there is a better way than this, because this is some pretty inconvenient syntax.
UPDATE:
This works:
OR,
If you have a foreign key ID defined in your model (as in a nullable ContactId), this becomes a lot easier.