我的控制器:
[HttpPost]
public ActionResult Deposit(DepositTicket dt)
{
using (var db = new MatchGamingEntities())
{
MembershipUser currentUser = Membership.GetUser();
Guid UserId = (Guid)currentUser.ProviderUserKey;
var MyAccount = from a in db.Accounts
where a.UserId == UserId
select new Account{
AccountId = a.AccountId,
Balance = a.Balance
};
BankTransaction transaction = new BankTransaction();
transaction.Amount = dt.Amount;
transaction.AccountId = MyAccount.SingleOrDefault().AccountId;
transaction.Created = DateTime.Today;
transaction.TransactionType = "Credit";
Debug.Write("Amount: " + transaction.Amount + " AccountId " + transaction.AccountId);
db.BankTransactions.AddObject(transaction);
MyAccount.SingleOrDefault().Balance += transaction.Amount;
//Update Query
db.SaveChanges();
return View();
}
如果评论“更新查询”是,我想添加更新查询以使用Account对象更新Account表。我想更新现有记录,这可以使用db.Accounts的预定义函数来完成,还是我必须写一个linq查询?
答案 0 :(得分:0)
似乎您要获得自定义帐户对象会遇到很多麻烦,然后只想更新原始帐户记录。我建议只使用原始帐户对象并进行必要的更新,然后在调用SaveChanges时,它将更新您的帐户记录。
以下是我建议的更改
public ActionResult Deposit(DepositTicket dt)
{
using (var db = new MatchGamingEntities())
{
MembershipUser currentUser = Membership.GetUser();
Guid UserId = (Guid)currentUser.ProviderUserKey;
var MyAccount = db.Accounts.SingleOrDefault(a => a.UserId == UserId);
BankTransaction transaction = new BankTransaction();
transaction.Amount = dt.Amount;
transaction.AccountId = MyAccount.AccountId;
transaction.Created = DateTime.Today;
transaction.TransactionType = "Credit";
Debug.Write(String.Format("Amount: {0} AccountId: {1}", transaction.Amount, transaction.AccountId);
db.BankTransactions.AddObject(transaction);
MyAccount.Balance += transaction.Amount;
db.SaveChanges();
return View();
}
希望这有帮助。
答案 1 :(得分:0)
db.SaveChanges();
将为您执行更新,除非您在db中预定义了SP。