无法设法将多对一关联设置为空并保存实体
假设我有:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试让“赞助商”成为虚拟财产。根据您的配置,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.