从一个的DbContext所有跟踪的实体? [英] Get all tracked entities from a DbContext?

查看:108
本文介绍了从一个的DbContext所有跟踪的实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

许多我的数据库中的表的需要有一个dateCreated会和DateModified」栏。我想更新这些列每当的SaveChanges()被调用。

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.

我所有的模型对象从一个类继承 AbstractModel 允许这种行为。这个类看起来是这样的:

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() { }
}

然后我打算重写 UpdateDates()在具有 dateCreated会 DateModified 领域,他们需要维持的子类。

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

要使用这个,我需要能够得到所有实体的列表,该的DbContext 是跟踪,并调用 UpdateDates()上他们,如果该对象被标记为添加修改

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.

我似乎无法获得访问到哪里的DbContext 是存储该信息。我可以做 dbContext.Entry(对象).STATE 来获得 EntityState 一个单独的实体,但我可以'科技工作如何让所有跟踪的实体的列表。

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.

我如何做到这一点?

推荐答案

我想你可以使用的 ChangeTracker 此:

public class MyContext : DbContext
{
    //...

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

    }
}

这篇关于从一个的DbContext所有跟踪的实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆