Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all tracked entities from a DbContext?

Many of the tables in my database need to have a "DateCreated" and "DateModified" column. I want to update these columns whenever SaveChanges() is called.

All my model objects inherit from a class AbstractModel to allow this kind of behavior. The class looks like this:

public abstract class AbstractModel {
    public virtual void UpdateDates() { }
}

I then plan to override UpdateDates() in any child classes that have DateCreated and DateModified fields they need to maintain.

To use this, I need to be able to get a list of all the entities that the DbContext is tracking, and call UpdateDates() on them if the object is marked as being Added or Modified.

I can't seem to get access to wherever DbContext is storing this information. I can do dbContext.Entry(object).State to get the EntityState of a single entity, but I can't work out how to get a list of all tracked entities.

How do I do this?

like image 436
Oliver Avatar asked Apr 12 '12 11:04

Oliver


1 Answers

I think you can use the ChangeTracker for this:

public class MyContext : DbContext
{
    //...

    public override int SaveChanges()
    {
        foreach (var dbEntityEntry in ChangeTracker.Entries<AbstractModel>())
        {
            dbEntityEntry.Entity.UpdateDates();
        }
        return base.SaveChanges();

    }
}
like image 172
nemesv Avatar answered Sep 30 '22 07:09

nemesv