Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

c# - An entity object cannot be referenced by multiple instances of IEntityChangeTracker. On multiple entries

I have a work object:

public class Work{
public int WorkId { get; set; }
public virtual Work RelatedWork { get; set; }
public virtual ICollection<Work> RelatedMultipleWorks { get; set; }
}

I'm generating an Work object like this :

Work myWork = new Work();

work mywork2 = new Work();
work mywork3 = new Work();

myWork.RelatedMultipleWorks.add(mywork2);
myWork.RelatedMultipleWorks.add(mywork3);

On DbSaveChanges, I get this exception :

An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

What is wrong with the code? How can I fix this? Thanks.

I get the exception at this line :

_db.Works.Add(mywork);

Here is my DbSaveChanges Line :

  _db.Works.Add(_myWork);
  _db.SaveChanges();
  result.Success= true;
  _provider.AddOrUpdate(mywork);

Note : In the actual code, Work entity has a lot more entities. Like hundreds, so I can't post actual code.

EDIT : When I try to add myWork2 or myWork3 using _db.Works.Add(_myWork2);, I still get the same error. Is this error because of a missing entity or something like that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Ultimately, this is the same problem mentioned here: How can I use EF to add multiple child entities to an object when the child has an identity key?

If you have a auto generated PK and attempt to do an Add after doing a previous udpate/delete on the same context, it will crash because you end up with the same PKs for multiple objects at the same time.

To fix this, you must either set all those WorkIds (I assume this is the PK) to -1, -2, -3 and their proper FK references to those new numbers
OR
You must add all new entities first before you do any updates/deletes since EF will realize that those IDs will be set in the future.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...