Click here to Skip to main content
15,886,362 members
Articles / Hosted Services / Azure

Kerosene ORM: a dynamic, configuration-less and self-adaptive ORM for POCO objects supporting a SQL-like syntax from C#

Rate me:
Please Sign up or sign in to vote.
4.96/5 (71 votes)
1 Mar 2015CPOL35 min read 542.1K   4.6K   212  
The seventh version of the dynamic, configuration-less and self-adaptive Kerosene ORM library, that provides full real support for POCO objects, natural SQL-like syntax from C#, and advanced capabilities while being extremely easy to use.
// ======================================================== DataUpdate.cs
namespace Kerosene.ORM.Maps.Concrete
{
	using Kerosene.ORM.Core;
	using Kerosene.ORM.Core.Concrete;
	using Kerosene.Tools;
	using System;
	using System.Collections;
	using System.Collections.Generic;
	using System.Linq;
	using System.Text;

	// ==================================================== 
	/// <summary>
	/// Represents an update operation for its associated entity.
	/// </summary>
	public class DataUpdate<T> : MetaOperation<T>, IDataUpdate<T>, ICoreCommandProvider where T : class
	{
		/// <summary>
		/// Initializes a new instance.
		/// </summary>
		/// <param name="map">The map this command will be associated with.</param>
		/// <param name="entity">The entity affected by this operation.</param>
		public DataUpdate(DataMap<T> map, T entity) : base(map, entity) { }

		/// <summary>
		/// Generates a new command that when executed implements the operation this instance
		/// refers to, or null if the state of this instance impedes such core command to be
		/// create
		/// </summary>
		/// <returns>A new command, or null.</returns>
		internal IUpdateCommand GenerateCoreCommand()
		{
			return IsDisposed ? null : Map.GenerateUpdateCommand(Entity);
		}
		ICommand ICoreCommandProvider.GenerateCoreCommand()
		{
			return this.GenerateCoreCommand();
		}

		/// <summary>
		/// Invoked when submitting this operation.
		/// </summary>
		protected override void OnSubmit()
		{
			List<object> list = null;

			// Parent dependencies are inserted or updated as appropriate...
			list = MetaEntity.GetDependencies(MemberDependencyMode.Parent); foreach (var obj in list)
			{
				if (obj == null) continue;
				var objType = obj.GetType(); if (!objType.IsClass) continue;
				var objMeta = MetaEntity.Locate(obj);
				var objMap = objMeta.Map ?? Repository.RetrieveUberMap(objType);

				if (objMap == null) continue;
				if (!object.ReferenceEquals(Repository, objMap.Repository))
					throw new InvalidOperationException(
						"Entity '{0}' is not managed by repository '{1}'."
						.FormatWith(obj.Sketch(), Repository));

				switch (objMeta.State)
				{
					case MetaState.Detached:
						objMap.Insert(obj).Submit();
						break;

					case MetaState.Ready:
						if (objMeta.UpdateNeeded()) objMap.Update(obj).Submit();
						objMeta.ToRefresh = true;
						break;

					case MetaState.ToDelete:
						objMeta.Operation.Dispose();
						objMeta.ToRefresh = true;
						break;

					default:
						objMeta.ToRefresh = true;
						break;
				}
			}
			list.Clear(); list = null;

			// Reordering...
			Repository.UberOperations.Remove(this);
			Repository.UberOperations.Add(this);

			// Removed childs are deleted...
			list = MetaEntity.DetectRemovedChilds(); foreach (var obj in list)
			{
				if (obj == null) continue;
				var objType = obj.GetType(); if (!objType.IsClass) continue;
				var objMeta = MetaEntity.Locate(obj);
				var objMap = objMeta.Map ?? Repository.RetrieveUberMap(objType);

				if (objMap == null) continue;
				if (!object.ReferenceEquals(Repository, objMap.Repository))
					throw new InvalidOperationException(
						"Entity '{0}' is not managed by repository '{1}'."
						.FormatWith(obj.Sketch(), Repository));

				if (objMeta.Operation != null)
				{
					if (!(objMeta.Operation is IDataDelete))
					{
						objMeta.Operation.Dispose();
						objMap.Delete(obj).Submit();
					}
				}
				else objMap.Delete(obj).Submit();
			}
			list.Clear(); list = null;

			// Child dependencies are inserted or updated as appropriate...
			list = MetaEntity.GetDependencies(MemberDependencyMode.Child); foreach (var obj in list)
			{
				if (obj == null) continue;
				var objType = obj.GetType(); if (!objType.IsClass) continue;
				var objMeta = MetaEntity.Locate(obj);
				var objMap = objMeta.Map ?? Repository.RetrieveUberMap(objType);

				if (objMap == null) continue;
				if (!object.ReferenceEquals(Repository, objMap.Repository))
					throw new InvalidOperationException(
						"Entity '{0}' is not managed by repository '{1}'."
						.FormatWith(obj.Sketch(), Repository));

				switch (objMeta.State)
				{
					case MetaState.Detached:
						objMap.Insert(obj).Submit();
						break;

					case MetaState.Ready:
						if (objMeta.UpdateNeeded()) objMap.Update(obj).Submit();
						objMeta.ToRefresh = true;
						break;

					default:
						objMeta.ToRefresh = true;
						break;
				}
			}
			list.Clear(); list = null;
		}

		/// <summary>
		/// Invoked when executing this operation against the database.
		/// </summary>
		protected override void OnExecute()
		{
			var cmd = GenerateCoreCommand(); try
			{
				if (cmd != null)
				{
					MetaEntity.ValidateRowVersion();

					var rec = (IRecord)cmd.First(); if (rec != null)
					{
						MetaEntity.SetRecord(rec, disposeOld: true);
						MetaEntity.Map.LoadEntity(rec, MetaEntity.Entity);
						MetaEntity.ToRefresh = true;
					}
					else throw new DatabaseException(
						"Error executing '{0}'."
						.FormatWith(cmd.TraceString()));
				}
			}
			finally { if (cmd != null) cmd.Dispose(); }
		}
	}
}
// ======================================================== 

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Spain Spain
mbarbac has worked in start-ups, multinational tech companies, and consulting ones, serving as CIO, CTO, SW Development Director, and Consulting Director, among many other roles.

Solving complex puzzles and getting out of them business value has ever been among his main interests - and that's why he has spent his latest 25 years trying to combine his degree in Theoretical Physics with his MBA... and he is still trying to figure out how all these things can fit together.

Even if flying a lot across many countries, along with the long working days that are customary in IT management and Consultancy, he can say that, after all, he lives in Spain (at least the weekends).

Comments and Discussions