ASP.NET MVC3 Code-First Error- attempting to update entity

后端 未结 2 1646
北恋
北恋 2021-01-03 10:10

I\'ve checked this question and it seems to be related to what I need, but does not answer it exactly.

I have an entity (Sql Compact using EF Code First via MVC3- if

2条回答
  •  一个人的身影
    2021-01-03 10:56

    The short answer is that you've already loaded the entity into the context with the Find and you cannot later attach another one.

    You are left with two options:

    • Detach the first instance, then attach the second
    • Copy the fields from the second instance to the first

    I'll share code for the first option. First, add a Detach method to your DbContext implementation:

    public void Detach(object entity)
    {
        var objectContext = ((IObjectContextAdapter)this).ObjectContext;
        objectContext.Detach(entity);
    }
    

    Then call Detach instead of setting the variable to null

    var startingIssue = db.Issues.Find(issue.IssueId);
    if (ModelState.IsValid)
    {
        if (issue.CreatedBy != startingIssue.CreatedBy) issue.CreatedBy = startingIssue.CreatedBy;
        if (issue.CreatedDate != startingIssue.CreatedDate) issue.CreatedDate = startingIssue.CreatedDate;
        issue.LastActivity = (DateTime?)DateTime.Now.Date;
        if (issue.ClosedBy != null) issue.ClosedDate = (DateTime?)DateTime.Now.Date;
    
        // startingIssue = null;
        db.Detach(startingIssue);
    
        db.Entry(issue).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    

提交回复
热议问题