Is it possible to get all the monitored things from a DbContext?

c# entity-framework


My database needs "DateCreated" and "DateModified" columns in several of the tables. When necessary, I wish to update these columns.SaveChanges() is known as.

My model's objects all descended from a class.AbstractModel to accept this kind of conduct. The class appears as follows:

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

I'll then override it.UpdateDates() any lessons for kids that haveDateCreated and DateModified fields that need upkeep.

I need to be able to get a list of every entity that theDbContext is monitoring and callingUpdateDates() If the item has a marking indicating it isAdded or Modified .

I can't seem to access anything, anywhereDbContext is preserving this data. I am capable.dbContext.Entry(object).State to obtainEntityState I know how to retrieve a list of all monitored entities for a single object, but not for the whole list.

What should I do?

4/12/2012 11:16:22 AM

Accepted Answer

I believe you can do this with the ChangeTracker:

public class MyContext : DbContext

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

4/12/2012 11:28:08 AM

Popular Answer

We encountered problems, such as the in memory database we used in the test environment not functioning properly with the above method, which is why we believe the acceptable solution here is superior for usage above EF4 (getting Detached state for some modified entries in inheritance scenarios). The tracked entities are retrieved using the native DbContext method in the following way:

        .Where (t => t.State == EntityState.Modified)

Related Questions


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