ObjectContextExtensions

This is a class of some useful extensions for the ObjectContext which make it more maintainable. I’ve always hated having to use strings in code and the ApplyCurrentValues method uses them. This code gets around that, so that you can now use:

context.ApplyCurrentValues<EntityType>(context.GetEntitySetFullName<EntityType>(), objEntity;

and it works fine, even if you change the underlying table name.

using System;
using System.Linq;
using System.Collections.Generic;
using System.Data.Objects.DataClasses;
using System.Data.Objects;
using System.Data.Metadata.Edm;

namespace System
{
	public static class ObjectContextExtensions
	{
		public static string GetEntitySetFullName(this ObjectContext context, EntityObject entity)
		{
			// If the EntityKey exists, simply get the Entity Set name from the key
			if (entity.EntityKey != null)
			{
				return entity.EntityKey.EntitySetName;
			}
			else
			{
				string entityTypeName = entity.GetType().Name;
				var container = context.MetadataWorkspace.GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace);
				string entitySetName = (from meta in container.BaseEntitySets
										where meta.ElementType.Name == entityTypeName
										select meta.Name).First();

				return container.Name + "." + entitySetName;
			}
		}
		public static string GetEntitySetFullName<TEntityType>(this ObjectContext context) where TEntityType : EntityObject
		{
			Type entityType = typeof(TEntityType);
			string entityTypeName = entityType.Name;
			var container = context.MetadataWorkspace.GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace);
			string entitySetName = (from meta in container.BaseEntitySets
									where meta.ElementType.Name == entityTypeName
									select meta.Name).First();

			return container.Name + "." + entitySetName;
		}

		public static TEntityType ApplyCurrentValues<TEntityType>(this ObjectContext context, TEntityType persistedObject)
			where TEntityType : EntityObject
		{
			return
				context.ApplyCurrentValues<TEntityType>
					(context.GetEntitySetFullName<TEntityType>(), persistedObject);
		}
		public static void AddObject<TEntityType>(this ObjectContext context, TEntityType persistedObject)
		   where TEntityType : EntityObject
		{
			context.AddObject(context.GetEntitySetFullName<TEntityType>(), persistedObject);
		}
	}
}




Advertisements

About this entry