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

c# data-binding entity-framework events

Question

When information in a certain database that is represented by an entity model changes, I want to be alerted. Is the model aware of changes to the underlying data? How can I subscribe to an event if it really fires one?

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

Accepted Answer

Actually, your question is not really clear.

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

Why does it matter?

Do you wish to be alerted about database changes that your application did not make? If so, the response is that EF does not provide such a notification mechanism. You have to create your own.

Do you want to be informed when you make changes to your entities? The interface is INotifyPropertyChanged, and the navigation properties are ObservableCollection. To be able to trigger events when an entity changes, utilize these constructions in your entities.

Do you wish to know what database modifications will be made? OverrideSaveChanges or manageSavingChanges and putObjectStateManager to get the list of altered entities. Zzz-40-Zzz serves as an example of how to get a list of newly added entities of a certain kind.

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

Popular Answer

The functionality of subscribing to an Entity for inserts, updates, and deletions is elegantly condensed in the EntityFramework.Triggers NuGet package.

Just use the DbContextWithTriggers to surround your context;

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

then follow 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