Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to detect when a certain entity is added to the database in Entity Framework 6?

Let's say I have an entity called X. Whenever a new X entry is added to the database in any part of my code (db.Xs.Add(new_X_instance);) I want to execute a specific sql query using entity framework. I wonder if this is possible. Just to let you know, I am not able to use SQL Server triggers.

like image 877
renakre Avatar asked May 13 '16 12:05

renakre


People also ask

How do I track changes in Entity Framework?

In Entity Framework, change tracking is enabled by default. You can also disable change tracking by setting the AutoDetectChangesEnabled property of DbContext to false. If this property is set to true then the Entity Framework maintains the state of entities.

How does EF core detect changes?

By default, EF Core creates a snapshot of every entity's property values when it is first tracked by a DbContext instance. The values stored in this snapshot are then compared against the current values of the entity in order to determine which property values have changed.

What difference does AsNoTracking () make?

The AsNoTracking() extension method returns a new query and the returned entities will not be cached by the context (DbContext or Object Context). This means that the Entity Framework does not perform any additional processing or storage of the entities that are returned by the query.

What is the use of DbContext in Entity Framework?

A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that it can be used to query from a database and group together changes that will then be written back to the store as a unit. DbContext is conceptually similar to ObjectContext.


1 Answers

You can override SaveChanges() method in DbContext class and in there you can get a list of new added entities.

public override int SaveChanges()
{
    var AddedEntities = ChangeTracker.Entries<Entity>().Where(E => E.State == EntityState.Added).ToList();

    AddedEntities.ForEach(E => 
    {
        // Do whatever you like !
    });

    return base.SaveChanges();
}
like image 86
Kahbazi Avatar answered Sep 21 '22 13:09

Kahbazi