c# - Notifications for tracked changes in EntityFrameworks DbContext -
i building data entry app using entity framework user can fill out forms , save or cancel. want save button enabled when there actual data can saved database.
i know dbcontext.changetracker. not able find possibility notification form context whenever there changes.
of couse track manually, tedious , error prone.
update app winforms application
question: how can notification dbcontext when "is dirty/has changes"?
update 2
maybe can clarify question:
this don't want:
using(var ctx = new dbcontext()) { var foo = new fooentity(); ctx.add(foo); raisecontextisdirty(); //<-- don't want this, should automatic //..... ctx.savechanges(); raisecontextisclean(); //<-- don't want this, should automatic }
what looking this:
using(var ctx = new dbcontext()) { ctx.changetracker.ondirtychanged += contextdirtychanged; var foo = new fooentity(); ctx.add(foo); //<- fires ondirtychanged //..... ctx.savechanges(); //<- fires ondirtychanged }
you can use code dbcontext.hasunsavedchanges
property:
public partial class mydbcontext { public bool hasunsavedchanges { { try { return this.changetracker.entries().any(e => e.state == entitystate.added || e.state == entitystate.modified || e.state == entitystate.deleted); } catch (system.invalidoperationexception) { return false; } } }
in wpf enough set canexecute
condition of wpf command save
.
the problem in windows forms need find event fire enough , disable or enable button, not often. not think there property observer built in entityframework provide such events you.
you can check dbcontext.hasunsavedchanges
on every mouse or key event on form or that, similar how wpf works internally, see - http://northhorizon.net/2012/better-commands-in-wpf/.
Comments
Post a Comment