开发者

Update object on saving

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 OnPro开发者_Python百科pertyChanged but that is not the right override, as it is also called when loading the object.


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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜