Update object on saving

≯℡__Kan透↙ 提交于 2019-12-11 06:45:46

问题


I have an entity class (using model first, if that matters) that should persist its own last change date.

Is there a way to update this on saving? Right now I have only found overriding OnPropertyChanged but that is not the right override, as it is also called when loading the object.


回答1:


You can override SaveChanges on your ObjectContext derived class and modify the last change date just before saving. Something like:

public override int SaveChagnes(SaveOptions saveOptions)
{
    var entities = ObjectStateManager.GetObjectStateEntries(EntityState.Modified)
                                     .Where(e => !e.IsRelationship)
                                     .Select(e => e.Entity)
                                     .OfType<YourEntityType>();

    var currentDate = DateTime.Now;
    foreach(var entity in entities)
    {
        entity.LastChangedDate = currentDate;
    }

    return base.SaveChanges(saveOptions);
}


来源:https://stackoverflow.com/questions/5991383/update-object-on-saving

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!