Moerwald
Moerwald

Reputation: 11264

Delete and query, without DbContext.SaveChanges

Entity know-how question. Given the following code:

...
var entitiesToRemove = dbSet.Where (entity => entity.TimeToLive > 5);
dbSet.RemoveRange(entitiesToRemove);
var resultEntities = dbSet.Where(entity => /* some condition that will also match before deleted entities*/);
...

Question: Will the beforehand deleted entities also be included in resultEntities or not? Do I've to call DbContext.SaveChanges after dbSet.RemoveRange ?

Thx

Upvotes: 4

Views: 2187

Answers (3)

Pavvy
Pavvy

Reputation: 348

You need to do dbcontext.SaveChanges() before doing further processing. In dbSet.RemoveRange(entitiesToRemove), EF just have marked those entities for deletion. Which will reflect on db only after you call the SaveChanges().

Upvotes: 2

Dronacharya
Dronacharya

Reputation: 1281

Yes, the beforehand deleted entities will be included in resultEntities. Beacause, the RemoveRange didn't get reflected to the database. And, then when you are getting the results for resultEntites, you are querying the database, so it would result in the deleted values as well.

If you don't want the removed values to appear then you should call the Dbcontext.Savechanges() after RemoveRange.

Hope this helps.

Upvotes: 1

Sham
Sham

Reputation: 11

Yes, I think DbContext.SaveChanges should go after dbSet.RemoveRange

Upvotes: 1

Related Questions