如果修改了详细信息实体,为什么 EntityFramework 会更新主从关系中的主实体?

发布于 2024-12-15 08:28:25 字数 875 浏览 1 评论 0原文

我在数据库中有一个非常简单的主从结构,可以使用以下模型通过实体框架访问:

Entity Framework model
主实体修改通过插入/更新/删除存储过程进行映射。

详细信息实体被加载并编辑,它的主实体也被加载到上下文中,但不会被修改。保存更改后,即使主实体根本没有更改,详细实体和主实体都会更新(详细实体 => 参数化更新语句;主实体 => 更新存储过程调用)。

using (var context = new PlayGroundEntities())
{
    var master = context.Masters.First(m => m.MasterId == MasterAId);
    var detail = context.Details.First(d => d.DetailId == MasterADetail1Id);
    detail.DetailValue = "Detail Value";
    context.SaveChanges();
}

这对我来说很奇怪,如果不修改主实体,我想摆脱主实体更新 sp 调用。 如果主实体更新不是通过存储过程映射(正常的 ef 东西,生成简单的参数化插入/更新/删除 sql 语句),这种奇怪的行为就不会发生。

这只是一个非常简单的例子。在实际的项目中,我有一个复杂的模型,其中发生了同样的问题,我真的很想摆脱它。不幸的是,我确实必须使用存储过程映射,并且“主”实体的加载也很重要。

有人经历过类似的事情或设法以某种方式摆脱它吗? 我使用的是随 .NET Framweork 4.0 一起发布的 Entity Framework 4.0。

预先感谢您的帮助!

I have a very simple master-detail structure in database which is accessed via Entity Framework using the following model:

Entity Framework model

Master entity modifications are mapped via Insert/Update/Delete stored procedures.

A Detail entity is loaded and edited and it's Master entity is loaded into the context as well but that is not modified. When changes are saved both Detail and Master entities are updated even though the Master entity was not changed at all (Detail entity => parameterized update statement; Master entity => update stored procedure call).

using (var context = new PlayGroundEntities())
{
    var master = context.Masters.First(m => m.MasterId == MasterAId);
    var detail = context.Details.First(d => d.DetailId == MasterADetail1Id);
    detail.DetailValue = "Detail Value";
    context.SaveChanges();
}

This is very strange for me and I would like to get rid of the Master entity update sp call if the Master entity is not modified.
If Master entity updates are not mapped via stored procedures (normal ef stuff, simple parameterized insert/update/delete sql statements are generated) this strange behavior does not occur.

This is just a very simple example. In the real project I have a complex model where the same problem occurs and I would like really much to get rid of that. Unfortunately I really have to use the stored procedure mappings and the loading of the "Master" entity is also important.

Did anybody experience something like this or managed to get rid of it somehow?
I am using Entity Framework 4.0 released with .NET Framweork 4.0.

Thank You in advance for Your help!

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

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

发布评论

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

评论(1

辞慾 2024-12-22 08:28:25

我不太确定,但也许这会有帮助,所以尝试分离 master 以摆脱 Master 实体更新 sp:

context.Detach(master);

I am not really sure, but maybe this will help, so try detach master in order to get rid of Master entity update sp:

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