Saving changes with Entity Framework causes detached entity duplicate

I'm making a survey program that has a list of questions that are pulled from the database as entities. During the course of the survey the properties of the entity may be edited, but I do not want these changes persisted to the database. So, I detach the questions after they are loaded into the dbcontext and access them via a dictionary.

The problem arises when I attempt to save an answer to the database. Since the answer entity is related to the question entity (that has been detached) a completely new question entity is then added to the database. I'm not sure why this is occurring as the answer entity being added contains the proper ID of the detached entity (when I look at it in the debugger). However, upon saving changes it gets updated to the ID of the newly created duplicate entity.

Is there a way to stop this behavior? Or alternatively, is there a way to make changes to an entity and not have them persist to the database even when SaveChanges is called on the context for writing a answer or a log entry to the database?

Here is the code that loads, then detatches the questions (items):

 public FixedLengthBlockElementRuntime(FixedLengthBlock block, RuntimeContext context) : base(block, context)
    {
        this._items = ((FixedLengthBlock)this.Element).ItemBank.Items.OfType<FixedLengthItem>().ToDictionary(x => x.ItemName, x => x);


        foreach(FixedLengthItem fixedLengthItem in this._items.Values)
        {
            this.Context.DetachEntity(fixedLengthItem);
        }
    }

And here is the code that adds the duplicate entry:

    public void SetResponse(Response response)
    {
        response.Session = this.Session;
        this.DbContext.Responses.AddObject(response);
        this.DbContext.SaveChanges();
    }

Note that Response has the proper ItemId until the point of Saving Changes.


You can set the MergeOption on your questions DbSet to be OverwriteChanges.

Context.Questions.MergeOption = MergeOption.OverwriteChanges;

You'll need to be sure you set that BEFORE you make the query for the questions for this to work properly however.

More reading on how MergeOptions work

链接地址: http://www.djcxy.com/p/5736.html

上一篇: 实体框架5更新记录

下一篇: 使用实体框架保存更改会导致分离的实体重复