entity framework - EntityFramework: How to exclude deleted objects from Queries -


the following code demonstrates problem having entity framework. assume 'bob' has many records in sessions table.

i expect sessioncountb 1 less sessioncounta:

using (var context = new myefcontext) {    int sessioncounta = (from in context.sessions                          a.user = 'bob' select a).count();     sessions firstsession = (from in context.sessions                                   a.user = 'bob').firstordefault();     context.sessions.deleteobject(firstsession);     int sessioncountb = (from in context.sessions                          a.user = 'bob' select a).count();      // expect sessioncountb == sessioncounta - 1 } 

i know deleteobject marks object deletion - savechanges makes deletion on database.

but should deleted object not excluded further queries perform on same data model, before calling savechanges?

solutions

  1. if u dont want see entities in deleted state, filter them explicitly

_context.sessions.where(a => _context.entry(a).state != entitystate.deleted);

  1. get "local" collection after load collection (var x = _context.accounts) db, y = x.local filter entities deleted state. note - without local u wont see freshly added entities in collection loaded db. great example , explanation

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -