如何在不创建新主键的情况下更新数据库

时间:2016-10-16 20:04:37

标签: c# asp.net sql-server singleton state

我在Visual Studio中练习asp.net并开发银行应用程序。我的班级图如下图所示。

enter image description here

我的Account子类同时使用单例和状态模式。更改状态检入帐户状态子类型检查它所属的状态。所有这些都是由BankAccount中的changestate方法启动的。当我对我的银行帐户余额计划进行更改时,会创建新的帐户状态AccountStateID并保存更改。我需要编辑状态和余额变化的记录,而不是AccountStateID

我的帐户状态子类型 changeStateCheck 的代码是:

public override void ChangeStateCheck(BankAccount bankAccount) 
{
    if (bankAccount.Description == "Mortgage")
    {
        bankAccount.AccountState = BronzeState.GetInstance();
    }
    else if (bankAccount.Balance > 0 && bankAccount.Balance < 5000)
    {
        bankAccount.AccountState = BronzeState.GetInstance();
    }
    else if (bankAccount.Balance > 5000.01 && bankAccount.Balance < 10000)
    {
        bankAccount.AccountState = SilverState.GetInstance();
    }
    else if (bankAccount.Balance > 10000.01 && bankAccount.Balance < 20000)
    {
        bankAccount.AccountState = GoldState.GetInstance();
    }
    else if (bankAccount.Balance > 20000.01)
    {
        bankAccount.AccountState = PlatinumState.GetInstance();
    }
}

对于bankAccount 更改状态

 public void changeState()
 {
     if (this.AccountStateId == 1)
         BronzeState.GetInstance().StateChangeCheck(this);
     else if (this.AccountStateId == 2)
         SilverState.GetInstance().StateChangeCheck(this);
     else if (this.AccountStateId == 3)
         GoldState.GetInstance().StateChangeCheck(this);
     else if (this.AccountStateId == 4)
         PlatinumState.GetInstance().StateChangeCheck(this);
}

只是为了在数据库中更新我编辑的记录,在控制器中添加方法ChangeState()。即

public ActionResult Edit(SavingAccount savingaccount)
    {
        if (ModelState.IsValid)
        {
            db.Entry(savingaccount).State = EntityState.Modified;
            savingaccount.ChangeState();
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.AccountStateId = new SelectList(db.AccountState, "AccountStateID", "Description");
        ViewBag.ClientId = new SelectList(db.Client, "ClientId", "FullName", savingaccount.ClientId);
        return View(savingaccount);
    }

0 个答案:

没有答案