简体   繁体   English

EF 6更新实体时行为异常

[英]EF 6 misbehaving when updating entity

I have an entity that has a list of events attached to itself... think of it as a list of "what happened to me"... 我有一个实体,上面附有一个events列表...将其视为“我发生的事情”列表...

Every event has a SourceUser which is an entity also... 每个事件都有一个SourceUser ,它也是一个实体...

The thing is: when I try to update an entity, a new event is created and the current user is stamped on this event, and when I call Update , EF 6 does not see the user as a existing user (I think it's recognizing it as new) and it's trying to insert it, which causes a primary key violation... 问题是:当我尝试更新实体时,会创建一个新事件,并在该事件上标记当前用户,并且当我调用Update ,EF 6不会将该用户视为现有用户(我认为它可以识别该用户)作为新的),并尝试将其插入,这会导致主键冲突...

How can I handle this? 我该如何处理? How can I tell EF that the event is new, but it's associated entities are not new?!? 我怎样才能告诉EF事件是新的,但是它关联的实体不是新的?!

EDIT1: 编辑1:
@Jonesy I inherited this code and (except for keywords) it's in portuguese so i dont think it's gonna make much sense but i can explain it! @Jonesy我继承了这段代码,并且(除了关键字)它是葡萄牙语的,所以我认为这没有什么意义,但是我可以解释! Here: When the user sends a request, i grab a token, and retrive the user from the database via authentication-filter and build a "context" object that has a "CurrentUser"... when creating the event, i just grab "CurrentContext.CurrentUser"... 此处:当用户发送请求时,我获取一个令牌,并通过身份验证过滤器从数据库中检索用户,并构建一个具有“ CurrentUser”的“上下文”对象...在创建事件时,我只是获取“ CurrentContext.CurrentUser“ ...

This issue presents itself when you are dealing with disconnected/detached Entity Framework POCO objects,. 当您处理断开/分离的Entity Framework POCO对象时,就会出现此问题。 as the DbContext doesn't track changes to entities. 因为DbContext不会跟踪对实体的更改。 Specifically, trouble occurs with entities participating in a many-to-many relationship, where the EF has hidden a “join table” from the model itself. 具体而言,参与多对多关系的实体会发生麻烦,其中EF在模型本身中隐藏了“联接表”。

The problem with detached entities is that the data context has no way of knowing what changes have been made to an object graph, without fetching the data from the data store and doing an entity-by-entity comparison – and that assuming it's possible to fetch the same way as it was originally. 分离实体的问题在于,如果不从数据存储中获取数据并进行逐个实体的比较,并且假设有可能获取数据,则数据上下文无法知道对对象图进行了哪些更改。与最初的方式相同。

This links may help you: 此链接可以帮助您:

Why Does Entity Framework Reinsert Existing Objects into My Database? 为什么实体框架将现有对象重新插入数据库中?

Solving the detached many-to-many problem with the Entity Framework 使用实体框架解决分离的多对多问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM