3axap
3axap

Reputation: 352

EF entity not set new value to property

I have entity class:

 public class Account : IAccount
 {
    [Key, ForeignKey("PUser")]
    public int IdUser { get; set; }
    public virtual User PUser { get; set; }

    [Required]
    public decimal Balance { get; set; }
  }

But when I try updating retrieve entity and set a new value to property Balance the value doesn't change.

Why this happen and how should I change it?

Account senderAccount = _context.Accounts.FirstOrDefault(u => u.IdUser == userSenderId);
if (senderAccount != null)
 senderAccount.Balance = 400;

After that senderAccount.Balance still have old value

Thnx

Upvotes: 1

Views: 152

Answers (1)

Adil Mammadov
Adil Mammadov

Reputation: 8676

Query is not sent to database until SaveChanges method is called. So what you have to do, is to add _context.SaveChanges(); line when you want to send query to database. In your case it should look like this:

Account senderAccount = _context.Accounts.FirstOrDefault(u => u.IdUser == userSenderId);
if (senderAccount != null)
 senderAccount.Balance = 400;
_context.SaveChanges();

Also, do not forget to crate context inside of using block if applicable. Read more here.

Upvotes: 4

Related Questions