Wednesday, 26 November 2008

DynamicData - Automatic Column Update For Entity Framework

Update to DynamicData - Automatic Column Update

See also the MSDN referance here:

How to: Execute Business Logic During Property Changes (Entity Framework)
How to: Execute Business Logic When Saving Changes (Entity Framework)
How to: Change Relationships Between Objects (Entity Framework)

namespace NorthwindModel
{

    public partial class NorthwindEntities
    {
        partial void OnContextCreated()
        {
            this.SavingChanges += new EventHandler(OnSavingChanges);
        }

        private static void OnSavingChanges(object sender, EventArgs e)
        {

            // This will populate the PasswordHash and PasswordSalt fields
            var stateManager = ((NorthwindEntities)sender).ObjectStateManager;
            var insertedEntities = stateManager.GetObjectStateEntries(EntityState.Added);

            foreach (ObjectStateEntry stateEntryEntity in insertedEntities)
            {
                if (stateEntryEntity.Entity is Customers)
                {
                    Customers cust = (Customers)stateEntryEntity.Entity;
                    cust.CreatedBy = HttpContext.Current.User.Identity.Name;
                    cust.CreatedOn = DateTime.Now;
                    cust.UpdatedBy = HttpContext.Current.User.Identity.Name; 
                    cust.UpdatedOn = DateTime.Now;
                }
            }

            var modifiedEntities = stateManager.GetObjectStateEntries(EntityState.Modified);
            foreach (ObjectStateEntry stateEntryEntity in modifiedEntities)
            {
                if (stateEntryEntity.Entity is Customers)
                {
                    Customers cust = (Customers)stateEntryEntity.Entity;
                    cust.UpdatedBy = HttpContext.Current.User.Identity.Name; 
                    cust.UpdatedOn = DateTime.Now;
                }
            }
        }
    }
}

In the above code the CreatedBy, CreatedOn, UpdateBy and UpdatedOn properties are automatically updated every time a record is modified or UpdateBy and UpdatedOn are modified when a record is updated.

Originally posted on ASP.Net Forum by Rick Anderson here Re: Setting a scaffolded column value

Sunday, 23 November 2008

Useful link from Rick Anderson

Have a look at this cool article by Rick here: Improving the FK field display: Showing two fields in Foreign Key columns with EF