简体   繁体   中英

How can I override DBContext.SaveChanges() in my Model

I have an issue where I want to override SaveChanges() as I need to check some values being saved to the database and change them before they are saved.

I know I can override SaveChanges() in the DBContext :

var changeSet = ChangeTracker.Entries<Page>();
if (changeSet != null)
{
    foreach (var entry in changeSet)
    {
        switch (entry.State)
        {
            case System.Data.EntityState.Added:
                if (((Page)entry.Entity).Parent_PageID == -1)
                    ((Page)entry.Entity).Parent_PageID = null;
            break;
        }
    }
}

but this will get messy very quickly if I need to do this on multiple models.

How can I do this per model?

Answering my own question here as I didn't find any help for this so it might help someone else down the line. SO seemed the best place to share this.


Make sure you have a base model (or interface) of some kind with the following declaration:

public class BaseModel
{
    public virtual void OnSaveChanges<T>(T Obj)
    {

    }
}

Add the override in your derived model:

public class Page : BaseModel
{
    //property declarations

    public override void OnSaveChanges<T>(T Obj)
    {
        base.OnSaveChanges<T>(Obj);
        Page model = Obj as Page;

        //Do something with the object.
        if (model.Parent_PageID == -1)
            model.Parent_PageID = null;

    }
}

Add the following into your derived DBContext class:

public override int SaveChanges()
{
    foreach (var changeSet in ChangeTracker.Entries())
    {
        var type = Type.GetType(changeSet.Entity.GetType().ToString());
        if (type != null)
            BaseModel Obj = (BaseModel)Convert.ChangeType(changeSet.Entity, type);
            Obj.OnSaveChanges(changeSet.Entity);
        }
    }            
    return base.SaveChanges();
}

This will now call SaveChanges() for all your models that derive from BaseModel which allows you to make any last minute changes.

Note: Sometimes you could just use the getter or setter of the var but due to the issue I had with Foreign keys, I wasn't able to in this case.

This can be easily adapted to add AfterSave events etc.

HTH some one else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM