简体   繁体   English

对DbContext的更改未保存-MVC实体框架

[英]Changes to DbContext not saved - MVC Entity framework

I have created a database and then an MVC solution using VisualStudio Exrpess 2013 for WEB and I created a ViewModel to display an Edit view with dropdown lists. 我使用VisualStudio Exrpess 2013 for WEB创建了一个数据库,然后创建了一个MVC解决方案,并且创建了一个ViewModel以显示带有下拉列表的Edit视图。 The view model includes just the property 'parlists' of type PartnerList, which is the model representing the main table of the database, and 2 properties of type SelectList which I use to create the dropdown lists in the view. 视图模型仅包括PartnerList类型的属性“ parlists”(代表数据库主表的模型),以及2个SelectList类型的属性,我将使用这些属性在视图中创建下拉列表。 The code of the viewmodel is as follows: viewmodel的代码如下:

public class FileStatusEdit
{
    public SelectList HoldingsStatus { get; set; }
    public SelectList RealGainStatus { get; set; }
    public PartnerList parlists { get; set; }
}

In the controller I have the following code for the HttpGet edit method: 在控制器中,我具有HttpGet编辑方法的以下代码:

    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        var viewModel = new FileStatusEdit
        {
            HoldingsStatus = new SelectList(db.Statuses, "Status_ID", "Status1", db.PartnerLists.Where(p => p.IntermediaryID == id).Single().AssetDataSource.HoldingsFile.Status_ID),
            RealGainStatus = new SelectList(db.Statuses, "Status_ID", "Status1", db.PartnerLists.Where(p => p.IntermediaryID == id).Single().AssetDataSource.RealGainFile.Status_ID),
            parlists = db.PartnerLists
            .Include(p => p.AssetDataSource)
            .Where(p => p.IntermediaryID == id)
            .Single()
        };
        if (viewModel.parlists == null)
        {
            return HttpNotFound();
        }
        return View(viewModel);
    }

This code is working fine and the view is correctly displaying a form with the dropdown lists. 该代码工作正常,并且视图正确显示了带有下拉列表的表单。 I omit the view code as it is quite long and propably not relevant. 我忽略了视图代码,因为它很长并且可能不相关。 So far so good. 到现在为止还挺好。 My Http Post Edit method, however, is not saving the changes to the database. 但是,我的Http Post编辑方法没有将更改保存到数据库。 The code is as follows: 代码如下:

    [HttpPost, ActionName("Edit")]
    [ValidateAntiForgeryToken]
    public ActionResult EditPost(FileStatusEdit newParList)

    {
        if (TryUpdateModel(newParList.parlists, "",
            new string[] { "Firstname", "Surname", "Category", "ClientID", "IntermediaryID", "ExternalRef", "RecordStatus", "Asset_Data_Source_ID", "New_Communication_Issued", "AssetDataSource", "HoldingsFile", "RealGainFile"}))

        {
            try
            {
                db.Entry(newParList.parlists).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            catch (RetryLimitExceededException)
            {
                ModelState.AddModelError("", "Unable to save changes.");
            }
        }
        return View(newParList);
    }

As you can see I am passing the viewmodel (newParList) to the EditPost method and then I update it using TryUpdateModel. 如您所见,我将视图模型(newParList)传递给EditPost方法,然后使用TryUpdateModel更新它。 By stepping into the debugging process I can see that the database record newParList.parlists is correctly updated with the user input, however when the step db.SaveChanges() is executed the program redirects to the Index view without saving the changes to the database. 通过进入调试过程,我可以看到数据库记录newParList.parlists已使用用户输入正确更新,但是当执行步骤db.SaveChanges()时,程序将重定向到Index视图,而不将更改保存到数据库。 I tried using Attach as suggested in some posts but I believe the attach step is already included in the line 'db.Entry(newParList.parlists).State = EntityState.Modified;' 我尝试按照某些帖子中的建议使用“附加”,但我相信附加步骤已包含在“ db.Entry(newParList.parlists).State = EntityState.Modified;”行中。 and that did not indeed solve the problem. 但这并不能真正解决问题。 I examined a lot of posts and tried different solutions but none of them worked so I would appreciate some help. 我检查了很多帖子,并尝试了不同的解决方案,但是它们都没有起作用,因此,我希望获得一些帮助。

I suspect you're missing the context add or update. 我怀疑您缺少上下文添加或更新。 Here's an example of how I handle the creation of a new record. 这是我如何处理新记录创建的示例。

For an update you would find the record first then save the changes. 对于更新,您将首先找到记录,然后保存更改。

 public void SaveCreatedMessage(Message message)
    {
        var dbEntry = _context.Message.Add(message);
        if (dbEntry != null)
        {
            // Create the new record
            dbEntry.CustomerID = message.CustomerID;
            dbEntry.MessageID = message.MessageID;
            dbEntry.Description = message.Description;
            dbEntry.Text = message.Text;
            dbEntry.IsRead = message.IsRead;
            dbEntry.CreatedOn = message.CreatedOn;
            dbEntry.CreatedBy = message.CreatedBy;

            _context.Message.Add(message);
        }

        _context.SaveChanges();
    }

I think I found the solution. 我想我找到了解决方案。 I was not updating the correct entity. 我没有更新正确的实体。 In my HttpPost Edit method I now replaced the following line: 现在,在我的HttpPost Edit方法中,替换了以下行:

                db.Entry(newParList.parlists).State = EntityState.Modified;

with: 与:

                db.Entry(newParList.parlists.AssetDataSource.HoldingsFile).State = EntityState.Modified;
                db.Entry(newParList.parlists.AssetDataSource.RealGainFile).State = EntityState.Modified;

Now my entities HoldingsFile and RealGainFile are updated after SaveChages() is executed. 现在,执行SaveChages()之后,我的实体HoldingsFile和RealGainFile会更新。

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

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