private void Button_Click(object sender, RoutedEventArgs e) { Regex re = new Regex("[^0-9.-]+"); if (string.IsNullOrEmpty(textbox1.Text) || re.IsMatch(textbox1.Text)) { MessageBoxResult mes = MessageBox.Show("请输入数字", "错误", MessageBoxButton.OK); } try { using (var context = new BankContext2()) { var vaultinfo = context.VaultInfo.Where(x => x.Account == "admin").FirstOrDefault(); if (vaultinfo == null) { vaultinfo = new VaultInfo { Id = Guid.NewGuid(), Account = "admin", Password = "******", Name = "管理员", Balance = 10000 }; context.VaultInfo.Add(vaultinfo); context.SaveChanges(); } var recordinfo = new RecordInfo { Id = Guid.NewGuid(), AccountId = vaultinfo.Id, Amount = Convert.ToDouble(textbox1.Text), Remark = "取钱", CreateTime = DateTime.Now }; recordinfo.Balance = vaultinfo.Balance - recordinfo.Amount; if (recordinfo.Balance < 0) { throw new Exception("余额不足!"); } vaultinfo.Balance = recordinfo.Balance; //添加 context.RecordInfo.Add(recordinfo); //更新 context.VaultInfo.Attach(vaultinfo); context.Entry(vaultinfo).State = System.Data.Entity.EntityState.Modified; //存储到数据库 context.SaveChanges(); } } catch (Exception ex) { MessageBoxResult mes2 = MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK); //throw new Exception(ex.Message); } MessageBoxResult mes3 = MessageBox.Show("操作成功", "提示", MessageBoxButton.OK); Close(); }
/// <summary> /// 重写OnStartup /// </summary> /// <param name="e"></param> protected override void OnStartup(StartupEventArgs e) { /// string connectionString = AppDomain.CurrentDomain.BaseDirectory + @"Data\"; //string connectionString = AppDomain.CurrentDomain.BaseDirectory; AppDomain.CurrentDomain.SetData("DataDirectory", connectionString); SQLiteBaseForEF.ExistsDBFile(connectionString, "Bank.s3db"); //初始一个admin账户 using (var context = new BankContext2()) { var info = context.VaultInfo.Where(x => x.Account == "admin").FirstOrDefault(); if (info == null) { info = new VaultInfo { Id = Guid.NewGuid(), Account = "admin", Password = "******", Name = "管理员", Balance = 10000 }; context.VaultInfo.Add(info); context.SaveChanges(); } //var upList = context.RecordInfo.Where(x => x.Remark == "测试").ToList(); //for (int i = 0; i < 5; i++) //{ // var recordinfo = new RecordInfo // { // Id = Guid.Empty, // AccountId = Guid.Empty, // Amount = 0, // Remark = "测试", // CreateTime = DateTime.Now // }; // upList.Add(recordinfo); //} //foreach(var item in upList) //{ // if(item.Id == Guid.Empty) // { // item.Id = Guid.NewGuid(); // context.RecordInfo.Add(item); // } // else // { // item.Remark = "测试"; // context.RecordInfo.Attach(item); // context.Entry(info).State = System.Data.Entity.EntityState.Modified; // } //} //context.SaveChanges(); //var recordinfo = new RecordInfo //{ // Id = Guid.NewGuid(), // AccountId = Guid.Empty, // Amount = 1, // Remark = "存钱", // CreateTime = DateTime.Now //}; } base.OnStartup(e); }