查找方法不为对象赋值

时间:2018-03-13 19:42:56

标签: c# linq

我有一个Web项目,一切正常,下面这行除了这个之外的其他模型。我只是需要一些关于从哪里开始寻找解决方案的信息。

当我调试它时,我发现它正在获取已编辑的所有新数据,但它没有将新数据分配给EditedtimeEntry。 EditedtimeEntry var具有旧数据而不是已编辑的新数据。我查看了timeEntry.Id,它的新编辑只是没有分配给EditedtimeEntry。没有异常或构建错误它只是不保存更改,看起来它不保存更改的原因是因为EditedtimeEntry var由于某种原因未获得分配给它的新数据。谁能指出我正确的方向?

TimeEntry EditedtimeEntry = db.TimeEntries.Find(timeEntry.Id);

以下是带有问题的Full方法:

public ActionResult Edit( [Bind(Include = "Id,Description,Rate,Paid,Tech,Company")] TimeEntry timeEntry)
{
    if (ModelState.IsValid)
    {

        TimeEntry EditedtimeEntry = db.TimeEntries.Find(timeEntry.Id);
        Technician tech = db.Technician.Single(m => m.PhoneNumber == timeEntry.Tech.PhoneNumber);
        EditedtimeEntry.Tech = tech;
        Company comp = db.Companies.Single(m => m.Name == timeEntry.Company.Name);
        EditedtimeEntry.Company = comp;
        db.Entry(EditedtimeEntry).State = EntityState.Modified;
        db.SaveChanges();

        return RedirectToAction("Index");
    }
    return View(timeEntry);
}

对于与此相同的其他模型,我还有其他方法可行。这是alsos模型

public class TimeEntry
{
    [Key]
    public Guid Id { get; set; }
    public DateTime StartTime { get; set; }
    public DateTime EndTime { get; set; }
    public string Description { get; set; }
    public Rate Rate { get; set; }
    public Technician Tech { get; set; }
    public bool Paid { get; set; }
    public Company Company { get; set; }

}

public enum Rate { Desktop, Network, Remote, Phone }

谢谢=)

1 个答案:

答案 0 :(得分:0)

基本上,你正在做的事情与你想要做的完全相反:)当你从数据库中恢复项目时,你只是让项目保持不变,仍然在数据库中。你想要的是更新数据库项,然后保存更改(使用EntityState.Modified然后SaveChanges())

您只想编辑timeEntry,以便在UI中完成的所有更改都会转换为DB:

public ActionResult Edit( [Bind(Include = "Id,Description,Rate,Paid,Tech,Company")] TimeEntry timeEntry)
    {
        if (ModelState.IsValid)
        {
            Technician tech = db.Technician.Single(m => m.PhoneNumber == timeEntry.Tech.PhoneNumber);
            timeEntry.Tech = tech;
            Company comp = db.Companies.Single(m => m.Name == timeEntry.Company.Name);
            timeEntry.Company = comp;
            db.Entry(timeEntry).State = EntityState.Modified;
            db.SaveChanges();

            return RedirectToAction("Index");
        }
        return View(timeEntry);
    }