Hi, @fatih uyanık. Welcome to Microsoft Q&A.
Reason
AsNoTracking
is generally used for read-only queries. The data queried using AsNoTracking
will be in the Detached
state. At this time, the queried object is the same as a normal object and is not tracked, so the database will not be affected after modification.
The tracked data is in the Unchanged
state, and when modified, it is in the Modified
state. Calling SaveChanges
will adjust the database for data in the Added
, Modified
, and Deleted
states.
var book1 = new Book() { Id = 1, Name = "Value" };
var book2 = await dataAccess._context.Books.AsNoTracking().FirstOrDefaultAsync();
var state1 = dataAccess._context.Entry(book1).State.ToString();
var state2 = dataAccess._context.Entry(book2).State.ToString();
/*
* state1:Detached state2:Detached
*/
var book3 = await dataAccess._context.Books.FirstOrDefaultAsync();
var state3 = dataAccess._context.Entry(book3).State.ToString();
book3.Name = "new value";
var state4 = dataAccess._context.Entry(book3).State.ToString();
/*
* state3:Unchanged state4:Modified
*/
dataAccess._context.Add(book1);
var state5 = dataAccess._context.Entry(book1).State.ToString();
dataAccess._context.Remove(book3);
var state6 = dataAccess._context.Entry(book3).State.ToString();
/*
* state5:Added state6:Deleted
*/
Solution
For the data you want to modify, you could query it first, modify it, and then cancel tracking by setting State
to EntityState.Detached
. For read-only data, use AsNoTracking
.
var book = await dataAccess._context.Books.FirstOrDefaultAsync();
book.Name = "new value 1";
await dataAccess.SaveChangesAsync();
dataAccess._context.Entry(book).State = EntityState.Detached;
book.Name = "new value 2";
await dataAccess._context.SaveChangesAsync();
//Result: new value 1 is stored in the database, but new value 2 is not saved
Why uncommitted changes are displayed on the UI
Generally, data queried from the database is saved in ObservableCollection
(this data is stored in memory). ObservableCollection
is bidirectionally bound to the UI
. When data is modified on the UI
, the ObservableCollection
(the data in memory will change accordingly) will also change accordingly. The data in the ObservableCollection
is used to update the database, but the update fails, and the existing data in the database is not updated to the ObservableCollection
. The ObservableCollection
still uses the original data in memory to bind to the UI
, so the latest data is still presented on the UI
.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.