4 May 2012

Entity Framework 4 Set Default SQL Values On Save Changes

EF doesn't use the default values that you may have specified in your SQL Table schema.

So stuff like "DateCreated" fields that have getutcdate() as their default SQL value won't get set automatically when a record is saved from Entity Framework.

To solve that particular problem, I use the following approach. I enclose two styles, one for use with EF DbContext (POCO / CodeFirst), and one with EF ObjectContext (the default used in EDMX generation).

Note that you put this code within a partial extension of your EF Context class i.e. public partial class MyContext : DbContext or public partial class MyContext : ObjectContext

DbContext
public override int SaveChanges()
{
	this.ChangeTracker.DetectChanges();

	ObjectContext ctx = ((IObjectContextAdapter)this).ObjectContext;

	List<ObjectStateEntry> objectStateEntryList = ctx.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Deleted)
																		.ToList();

	foreach (ObjectStateEntry entry in objectStateEntryList)
	{
		if (!entry.IsRelationship)
		{
			switch (entry.State)
			{
				case EntityState.Added:
					if (entry.Entity.HasProperty("DateCreated"))
						entry.Entity.GetType().GetProperty("DateCreated").SetValue(entry.Entity, DateTime.UtcNow, null);
					if (entry.Entity.HasProperty("DateModified"))
						entry.Entity.GetType().GetProperty("DateModified").SetValue(entry.Entity, DateTime.UtcNow, null);
					break;

				case EntityState.Modified:
					if (entry.Entity.HasProperty("DateModified"))
						entry.Entity.GetType().GetProperty("DateModified").SetValue(entry.Entity, DateTime.UtcNow, null);
					break;
			}
		}
	}

	return base.SaveChanges();
}
ObjectContext
public override int SaveChanges(SaveOptions options)
{
	this.DetectChanges();

	foreach (var insert in this.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added))
	{
		if (insert.Entity.HasProperty("DateCreated"))
			insert.Entity.GetType().GetProperty("DateCreated").SetValue(insert.Entity, DateTime.UtcNow, null);
		if (insert.Entity.HasProperty("DateModified"))
			insert.Entity.GetType().GetProperty("DateModified").SetValue(insert.Entity, DateTime.UtcNow, null);
	}

	foreach (var update in this.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Modified))
	{
		if (update.Entity.HasProperty("DateModified"))
			update.Entity.GetType().GetProperty("DateModified").SetValue(update.Entity, DateTime.UtcNow, null);
	}

	return base.SaveChanges(options);
}

No comments:

Post a Comment

Comments are very welcome but are moderated to prevent spam.

If I helped you out today, you can buy me a beer below. Cheers!