无法设法将多对一关联设置为空并保存实体

发布于 2024-11-18 09:39:05 字数 448 浏览 5 评论 0原文

假设我有:

public class Event {
   public int EventID { get; set; }
   ...
   public Sponsor Sponsor { get; set; }
}


public class Sponsor { get; set; }
   public int SponsorID { get; set; }
   ...
}

因此,活动可以有(但不一定有)赞助商。我可以创建一个活动,设置一个赞助商并保存它就可以了。

我不知道如何工作的是

Event event = context.Events.Find(id);
event.Sponsor = null;
context.SaveChanges();

上面的内容没有对数据库中的sponsorid列进行更改。

Say I have:

public class Event {
   public int EventID { get; set; }
   ...
   public Sponsor Sponsor { get; set; }
}


public class Sponsor { get; set; }
   public int SponsorID { get; set; }
   ...
}

So an Event can have, but does not necessarily have, a Sponsor. I can create an Event, set a Sponsor and save it just fine.

What I cannot figure out how to make work is

Event event = context.Events.Find(id);
event.Sponsor = null;
context.SaveChanges();

The above doesn't make a change to the sponsorid column in the database.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

飘落散花 2024-11-25 09:39:05

尝试让“赞助商”成为虚拟财产。根据您的配置,EF 不知道您是否已加载 Event.Sponsor 属性,如果还没有,它也不知道 Sponsor = null 是实际更改。 EF 生成了两种代理,具体取决于您的 POCO,EF 尚未为您的事件类生成自跟踪代理(例如,导航属性赞助商不是虚拟的),因此当它比较快照时前一个事件实体的“Sponsor”未加载,而更新后的事件实体的“Sponser”设置为 null,则假定您没有更改其值。

Try to make "Sponsor" a virtual property. Depending on your configuration, EF doesn't know whether your have already loaded the Event.Sponsor property and if you haven't it also doesn't know that Sponsor = null is an actuall change. There are two kinds of proxys generated by the EF and depending on your POCOs EF hasn't generated a self-tracking proxy for your Event-class (for example, the Navigation Property Sponsor isn't virtual), so when it compares the snapshots of the previous Event entity, where "Sponsor" wasn't loaded and the updated one, where "Sponser" was set to null, it assumes that you didn't change it's value.

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