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
- if u dont want see entities in deleted state, filter them explicitly
_context.sessions.where(a => _context.entry(a).state != entitystate.deleted);
- get "local" collection after load collection (
var x = _context.accounts
) db,y = x.local
filter entities deleted state. note - withoutlocal
u wont see freshly added entities in collection loaded db. great example , explanation
Comments
Post a Comment