简体   繁体   中英

Entity Framework Code-First Database Not Updating

I'm having issues updating a Boolean from 'false' to 'true' in my database.

I am using Asp.Net MVC5 in Visual Studio 2017, and have created a database (using entity framework code-first) to contain two tables - task and steps (one-to-many relationship).

The index.cshtml page is laid out to list all of the tasks along with their relevant steps, and then each step has a 'mark as completed' button beside it to change the 'completed' field in the steps entity from false to true.

Here is my code:

Steps.cs:

public class Steps
{
    [Key]
    public int Id { get; set; }
    public int StepNumber { get; set; }
    public string Description { get; set; }
    public ToDoTask Task { get; set; }
    public bool Completed { get; set; }
    public DateTime? CompletedDate { get; set; }
    public Client Client { get; set; }
}

Index.cshtml:

@foreach (var step in ViewData["steps"] as Dictionary<Steps, int>)
{
    if (step.Value == task.Id)
    {
        <p>Step Number: @step.Key.StepNumber</p>
        <p>Step Description: @step.Key.Description</p>

        using (@Html.BeginForm("MarkStepAsCompleted", "Tasks"))
        {
            <div class="col-md-2" style="display:none">
                @Html.TextBox("Id", @step.Key.Id)
            </div>
            <button  type="submit" >Mark As Completed</button>
        }

    }
}

TasksController.cs:

[HttpPost]
[AllowAnonymous]
public ActionResult MarkStepAsCompleted(FormCollection form)
{
    var completedStepId = Convert.ToInt32(form["Id"]);
    var completedStep = db.Steps.Where(s => s.Id == completedStepId).FirstOrDefault();

    StepMethods.MarkAsCompleted(completedStep);

    return Redirect("Index");
}

StepMethods.cs:

public static void MarkAsCompleted(Steps step)
{
    var context = new ApplicationDbContext();
    var stepid = step.Id;
    context.Steps.Find(stepid);

    step.Completed=true;

    context.SaveChanges();
} 

The application runs well with no errors and when I hit the 'Mark As Completed' button, it redirects to the index page as wanted. But when I check the table in Server Explorer, the value in the 'Completed' column still says false.

You are not updating the entity retrieved from the database, but instead the local instance. Change to this:

public static void MarkAsCompleted(Steps step)
{
    using (var context = new ApplicationDbContext())
    {
        step = context.Steps.Find(step.id); //use the retrieved instance
        step.Completed = true;

        context.SaveChanges();
    }
} 

Also, always use the using statement when working with ApplicationDbContext (or, in general, any class that implements the IDisposable interface)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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