AlessandroF
AlessandroF

Reputation: 562

How does DbContext.SaveChanges() work in C# when updating a table?

Consider the following piece of code:

Customer customer = database.Customers.Where((X) => X.SSN = ssn ).FirstOrDefault();
customer.name = "John";
database.SaveChanges()

It simply updates the row that satisfies the Where. My question is: How can "SaveChanges()" know what to update? It seems that it does not have access visibility to "customer" and it receives no parameters.

Upvotes: 2

Views: 3981

Answers (3)

user14458236
user14458236

Reputation:

Every time that you get a record from database EF tracks it and identifies by making an id for it. When SaveChanges call, it ask the ef to know which entity state has been changed and try to update database. But I recommend that set AsNoTracking when get an entity from database for performance issues.

Upvotes: 4

nsevens
nsevens

Reputation: 2835

Entity Framework uses a ChangeTracker internally. This keeps the state of an entity as you add, update or delete it from the DbContext.

So, when calling SaveChanges() the change tracker knows what entities and what updates to send.

More info:

https://entityframework.net/change-tracker or https://learn.microsoft.com/en-us/ef/core/querying/tracking

Upvotes: 4

Geert-Jan Thomas
Geert-Jan Thomas

Reputation: 21

Because the database context knows what the primary key is. Try to generate a database context for a table without a primary key and you will see that you get errors/warnings

Upvotes: 0

Related Questions