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

后端 未结 2 1619
北恋
北恋 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:53

    If the CreateDate and CreatedBy fields are not in the edit form, the update action object will not have the db values.

    The additional call to the db and resetting, as Ed's answer describes, can be avoided if you include those fields in the edit form. Then the normal model binding should pick them up and give them back to you on the update.

    0 讨论(0)
  • 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");
    }
    
    0 讨论(0)
提交回复
热议问题