实体框架代码优先数据库未更新

时间:2018-03-12 13:48:47

标签: c# entity-framework

我在更新布尔值时出现问题' false'真的'在我的数据库中。

我在Visual Studio 2017中使用Asp.Net MVC5,并创建了一个数据库(使用实体框架代码优先)来包含两个表 - 任务和步骤(一对多关系)。

index.cshtml页面用于列出所有任务及其相关步骤,然后每个步骤都有一个标记为已完成'旁边的按钮可以更改已完成的'步骤实体中的字段从false变为true。

这是我的代码:

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();
} 

应用程序运行良好,没有任何错误,当我点击“标记已完成”时按钮,它根据需要重定向到索引页面。但是,当我在服务器资源管理器中检查表时,&#39;已完成&#39;中的值。专栏仍然说错。

1 个答案:

答案 0 :(得分:4)

您不是更新从数据库检索的实体,而是更新本地实例。改为:

anchor  = @driver.find_element(:xpath, '//li[@id="dashboard_navbar_item"]/a')
classes = anchor.attribute('class')

expect(classes).to include('active')

此外,在使用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(); } } 时(或者,通常,任何实现using接口的类),始终使用ApplicationDbContext语句

相关问题