UpdateModel() 无法为导航属性(实体引用)分配新值
这种情况发生在 ASP.NET MVC 2、.NET 4 (EF 4) 中。我的 Address
实体具有对 Post
引用的引用。 Zip 是 Post
实体的主键。 Post
实体中的另一个属性是 CityName。在我看来,我允许用户更改地址的 CityName,该地址会自动(通过 jquery)加载相应的 Zip 并将其存储在隐藏字段中。
发布时,这两个值都会正确发布并绑定到 Address
的 Post 引用。但 UpdateModel() 无法更新它们。它表示 Zip 是实体实体密钥的一部分,无法更改。
我很乐意通过新的 Zip 加载 Post 实体,并手动将其分配给现有的 Address,但对于所有其他属性,我希望依赖 UpdateModel()。
我怎样才能做到这一点?人们可能会认为在 EF4 中这样的问题已经得到解决。
This happens in ASP.NET MVC 2, .NET 4 (EF 4). My Address
entity has a reference to the Post
reference. Zip is the primary key of the Post
entity. Another property in Post
entity is CityName. In my views I allow users to change the CityName for the address which automatically (via jquery) loads up the corresponding Zip and stores it inside a hidden field.
When posted, both values are posted fine and binded to the Address
's Post reference. But UpdateModel() fails to update them. It says that the Zip is part of the entity's Entity Key and cannot be changed.
I would gladly load up the Post entity by the new Zip and manually assign it to the existing Address but for all other properties I stall want to rely on UpdateModel().
How can I achieve that? One would think that in EF4 stuff like this has been resolved..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
默认情况下,实体框架生成的类对更改主键值施加限制。这很好。你不应该以任何理由改变 PK。在添加场景之外更改 PK 对于状态跟踪和系统的总体健康状况具有相当大的影响。
要解决此问题,您需要告诉 UpdateModel 不要使用排除参数更新主键。
By default the entity framework generated classes put restrictions on changing primary key values. This is good. You shouldn't change a PK for any reason at all. Changing PKs outside of add scenarios has pretty huge ramifications for state tracking and the general health of your system.
To solve this problem you want to tell UpdateModel not to update your primary keys using the exclude parameter.