When the data in an entity model changes, does it trigger an event?

c# data-binding entity-framework events

Question

I want to be notified when data changes within a particular table, represented by an entity model. Is the model aware of underlying data changes? If it does actually fire an event, how can I subscribe to it?

1
6
4/26/2011 2:25:54 PM

Accepted Answer

Your question is actually very unclear.

I want to be notified when data changes within a particular table, represented by an entity model.

What does it mean?

Do you want to be notified about changes in database not done by your application? Then the answer is: No EF doesn't provide any such notification system. You must build your own.

Do you want to be notified about changes you did to your entities? The the answer is INotifyPropertyChanged interface and ObservableCollection for navigation properties. use these constructs in your entities to be able to fire events when entity changes.

Do you want to know what changes will be executed in the database? Override SaveChanges or handle SavingChanges and use ObjectStateManager to get list of changed entities. Here is some example how to get list of added entities of given type.

6
5/23/2017 12:17:54 PM

Popular Answer

The NuGet package EntityFramework.Triggers nicely wraps up functionality of subscribing to an Entity for inserts, updates, and deletions.

Just wrap your context with the DbContextWithTriggers;

public class MyContext : DbContextWithTriggers {
    public DbSet<Person> People { get; set; }
}

Then subscribe to trigger events

var mycontext  = new MyContext() { TriggersEnabled = true };
Triggers<Person>.Inserting += entry =>
{
    Console.WriteLine($"Person: {entry.Entity}");
};


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow