This is a migrated thread and some comments may be shown as answers.

auto update fields on savechanges

1 Answer 57 Views
Development (API, general questions)
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
JIG
Top achievements
Rank 1
JIG asked on 23 Feb 2015, 11:59 AM
In the past we updated 2 properties on savechanges (lastUpdate (datetime) and LastStaffID (Guid)) but i can't seem to find out how i can manage this with DataAccess, only found a 1 field option so far.

Any suggestion on how i can achieve this?

example of how it was : 

foreach (Entity item in e.Entities)
            {
                if (item.EntityAspect.EntityState == EntityState.Modified)
                {
                    try
                    {
                        item.EntityAspect.EntityMetadata.DataProperties["LastUpdate"].SetValue(item, DateTime.Now);
                        item.EntityAspect.EntityMetadata.DataProperties["LastStaffID"].SetValue(item, Guid.Empty);
                    }
                    catch (Exception)
                    { ; }
                }
            }

1 Answer, 1 is accepted

Sort by
0
Kaloyan Nikolov
Telerik team
answered on 26 Feb 2015, 06:04 AM
Hello,

This can be easily achieved if you redefine the SaveChanges implementation in a partial class of you context. The code should something like this:

public partial class EntitiesModel1
{
    public new void SaveChanges()
    {
        var changes = base.GetChanges();
        var updates = changes.GetUpdates<IEnitity>();
        foreach (var u in updates)
        {
            u.ModifiedBy = "theUser";
            u.ModifiedOn = DateTime.Now;
        }
 
        base.SaveChanges();
    }
}

Here I rely on the fact that all entities in the model inherit from the IEntity interface where the ModifiedOn property is defined. You can define the interface in the Designer or as code if you are using fluent mapping. The code above will update the ModifiedOn property for each updated record that inherits from the IEntity interface. 

I hope this helps. Should you have any additional questions do not hesitate to get back to us. 

Regards,
Kaloyan Nikolov
Telerik
 
OpenAccess ORM is now Telerik Data Access. For more information on the new names, please, check out the Telerik Product Map.
 
Tags
Development (API, general questions)
Asked by
JIG
Top achievements
Rank 1
Answers by
Kaloyan Nikolov
Telerik team
Share this question
or