为什么在分配空值时我的 EF4.1 关系没有设置为空?

发布于 2024-11-03 07:18:24 字数 651 浏览 0 评论 0原文

在我的系统中,我有任务,可以选择将其分配给联系人。因此,在我的业务逻辑中,我有以下代码:

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

如果未指定联系人,则 contact 变量为 null。当我提交更改时,这应该使联系关系无效,但是我注意到99%的时间我都没有发生这种情况(我见过它发生一次,但之后并不一致一遍又一遍地单步执行此代码)。

当我调试时,我已验证 _contactChangedtrue 并且内部代码没有受到攻击。但是,在我跳过 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

久夏青 2024-11-10 07:18:25

哇。很好的问题。我能够确认/重现这一点,即使引用对象不是动态代理t.Contact = null; 不起作用!

到目前为止我得到的最好答案是:

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

我真的希望有比这更好的方法,因为这是一些非常不方便的语法。

更新:

这有效:

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

    task.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:

    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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文