Yacov
Yacov

Reputation: 1070

Auto manage and protect Created\Updated fields with Entity Framework 5

I want so every added\changed record will have a time stamp of creation\change.

But - so it will be easy to embed and easy to manage - automatically.

Upvotes: 0

Views: 62

Answers (1)

Yacov
Yacov

Reputation: 1070

Overwrite the 'DbContext' class or embed this in the '.tt' file (Codefirst \ DBFirst)

The code assume so you have the fields 'CreatedOn'\'ModifiedOn' inside the POCO.

If you don't have them, or you have only one - the code will work fine.

Be aware! If you use a extension (as this one) so allow you to do batch updates or changes from a stored procedure - this will not work

EDIT:

I found the source of my inspiration - thanks 'Nick' here

public override int SaveChanges()
{
    var context = ((IObjectContextAdapter)this).ObjectContext;
    var currentTime = DateTime.Now;
    var objectStateEntries = from v in context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified)
                                where v.IsRelationship == false && v.Entity != null
                                select v;

    foreach (var entry in objectStateEntries)
    {
        var createdOnProp = entry.Entity.GetType().GetProperty("CreatedOn");
        if (createdOnProp != null)
        {
            if (entry.State == EntityState.Added)
            {
                if (createdOnProp != null)
                {
                    createdOnProp.SetValue(entry.Entity, currentTime);
                }
            }
            else
            {
                Entry(entry.Entity).Property("CreatedOn").IsModified = false;
            }
        }

        var modifiedOnProp = entry.Entity.GetType().GetProperty("ModifiedOn");
        if (modifiedOnProp != null)
        {
            modifiedOnProp.SetValue(entry.Entity, currentTime);
        }
    }

    return base.SaveChanges();
}

Upvotes: 1

Related Questions