实体框架 4:保存父对象时如何获取子对象的原始值?

发布于 2024-11-15 12:51:03 字数 397 浏览 2 评论 0原文

我在SE上看到过很多与此相关的帖子,但没有一个能令人满意地回答这个问题。如果有一篇文章确实回答了这个问题(带有实际的代码示例),那么请指出我的方向。

我需要在保存对象时将信息写入日志。我需要知道原始值和新值。这对于父对象来说非常容易,甚至可以很容易地获取任何更改的子对象的值。挑战在于获取子对象的原始值。

例如,用户通过下拉列表更改子对象。这会更改父级上外键的值。保存时,我需要在日志中写入更改实体的文本描述(ToString() 值或其他值),而不是外键的值。

ObjectStateEntry 包含父对象的当前值和原始值,但是如何获取更改后的子对象的当前值和原始值?

看起来这应该是可能的,但要么太难实现,要么被微软设计团队忽视了。

预先感谢您的任何帮助。

I've seen lots of posts on SE relating to this, but none have answered the question satisfactorily. If there is a post that does answer this (with an actual code example) then please point me in that direction.

I need to write information to a log when saving an object. I need to know the original values and the new values. This is very easy for the parent object, and it is even fairly easy to get the new values on any changed child objects. The challenge is getting the original values of the child object.

For instance, a user changes a child object via a drop-down list. This changes the value of the foreign key on the parent. When saving, I need to write the textual description (the ToString() value or some other value) of the changed entity in the log, not the value of the foreign key.

The ObjectStateEntry contains the current values and original values of the parent, but how do I get the current and original values of the changed child object?

It seems like this is something that should be possible, but is either much too difficult to accomplish, or has been overlooked by the Microsoft design team.

Thanks in advance for any help.

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

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

发布评论

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

评论(1

萌辣 2024-11-22 12:51:03

就像你总是得到它一样:你查一下。请记住,在您的情况下,“子对象”甚至可能不会从数据库加载。在更改“父级”上的 FK 值之前,没有要求这样做。

听起来您实际上并没有更改“子对象”本身。相反,您只是更改了“父对象”以指向不同的子对象。

在这种情况下,我将使用 Context.GetObjectByKey() 根据原始 FK 值提取对象。如果它恰好被加载,则从内存中获取它,如果没有加载,则从数据库中获取它。

The same way you always get it: You look it up. Remember, in your case the "child object" might not even be loaded from the DB. There is no requirement to do so before changing the FK value on the "parent."

It doesn't sound like you actually changed the "child object" itself. Rather, you just changed the "parent" to point at a different child object.

In this case, I'd use Context.GetObjectByKey() to pull the object based on the original FK value. This grabs it from memory if it happens to be loaded, and from the DB if it doesn't.

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