Click here to Skip to main content
15,892,927 members
Articles / Database Development / SQL Server

Database-Driven Business Layer Templates

Rate me:
Please Sign up or sign in to vote.
4.61/5 (17 votes)
22 Jan 2008CPOL9 min read 51.1K   481   106  
A introduction to the flexibilities provided by the use of SQL extended properties in business layer code templates.
/*
===============================================================================
                     EntitySpaces(TM) by EntitySpaces, LLC
                 A New 2.0 Architecture for the .NET Framework
                          http://www.entityspaces.net
===============================================================================
                       EntitySpaces Version # 2007.1.1024.0
                       MyGeneration Version # 1.2.0.2
                           12/19/2007 2:29:31 PM
-------------------------------------------------------------------------------
*/


using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Data;
using System.ComponentModel;
using System.Xml.Serialization;


using EntitySpaces.Interfaces;
using EntitySpaces.Core;



namespace DAK.CustomESN.BusinessLayer
{
	
	[Serializable]
	[GeneratedCode]
	abstract public class esCustomerDemographicCollection : esEntityCollection, INotifyCollectionChanged
	{
		public esCustomerDemographicCollection()
		{

		}
		
		public event NotifyCollectionChangedEventHandler CollectionChanged;
		
		protected override string GetCollectionName()
		{
			return "CustomerDemographicCollection";
		}
		
		#region Query Logic
		protected void InitQuery(esCustomerDemographicQuery query)
		{
			query.OnLoadEvent += new esDynamicQuery.QueryLoadedDelegate(OnQueryLoaded);
			query.es.Connection = ((IEntityCollection)this).Connection;
		}

		protected bool OnQueryLoaded(DataTable table)
		{
			this.PopulateCollection(table);
			return (this.RowCount > 0) ? true : false;
		}
		#endregion
		
		virtual public CustomerDemographic DetachEntity(CustomerDemographic entity)
		{
			return base.DetachEntity(entity) as CustomerDemographic;
		}
		
		virtual public CustomerDemographic AttachEntity(CustomerDemographic entity)
		{
			return base.AttachEntity(entity) as CustomerDemographic;
		}
		
		virtual public void Combine(CustomerDemographicCollection collection)
		{
            base.Combine(collection);
        }
		
        new public CustomerDemographic this[int index]
        {
            get
            {
                return base[index] as CustomerDemographic;
            }
        }		
	}
	


	[Serializable]
	[GeneratedCode]
	abstract public class esCustomerDemographic : esEntity, INotifyPropertyChanged
	{
		virtual protected esCustomerDemographicQuery GetDynamicQuery()
		{
			return null;
		}
		
		public esCustomerDemographic()
		{
		}
	
		public esCustomerDemographic(DataRow row)
			: base(row)
		{
		}
		
		#region LoadByPrimaryKey
		public virtual bool LoadByPrimaryKey(System.String customerTypeID)
		{
			if(this.es.Connection.SqlAccessType == esSqlAccessType.DynamicSQL)
				return LoadByPrimaryKeyDynamic(customerTypeID);
			else
				return LoadByPrimaryKeyStoredProcedure(customerTypeID);
		}
	
		/// <summary>
		/// Loads an entity by primary key
		/// </summary>
		/// <remarks>
		/// EntitySpaces requires primary keys be defined on all tables.
		/// If a table does not have a primary key set,
		/// this method will not compile.
		/// </remarks>
		/// <param name="sqlAccessType">Either esSqlAccessType StoredProcedure or DynamicSQL</param>
		public virtual bool LoadByPrimaryKey(esSqlAccessType sqlAccessType, System.String customerTypeID)
		{
			if (sqlAccessType == esSqlAccessType.DynamicSQL)
				return LoadByPrimaryKeyDynamic(customerTypeID);
			else
				return LoadByPrimaryKeyStoredProcedure(customerTypeID);
		}
	
		private bool LoadByPrimaryKeyDynamic(System.String customerTypeID)
		{
			esCustomerDemographicQuery query = this.GetDynamicQuery();
			query.Where(query.CustomerTypeID == customerTypeID);
			return query.Load();
		}
	
		private bool LoadByPrimaryKeyStoredProcedure(System.String customerTypeID)
		{
			EntitySpaces.Interfaces.esParameters parms = new EntitySpaces.Interfaces.esParameters();
			parms.Add("CustomerTypeID",customerTypeID);
			return this.Load(esQueryType.StoredProcedure, this.es.spLoadByPrimaryKey, parms);
		}
		#endregion
		
        #region INotifyPropertyChanged Members

		public event PropertyChangedEventHandler PropertyChanged;

		protected void OnPropertyChanged(string propertyName)
		{
			if (PropertyChanged != null)
			{
				PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
			}
		}

        #endregion		
		
		#region Properties
		
        public override void SetProperties(IDictionary values)
        {
            foreach (string propertyName in values.Keys)
            {
                this.SetProperty(propertyName, values[propertyName]);
            }
        }

		public override void SetProperty(string name, object value)
		{
			if(this.Row == null) this.AddNew();
			
			esColumnMetadata col = this.Meta.Columns.FindByPropertyName(name);
			if (col != null)
			{
				if(value == null || value.GetType().ToString() == "System.String")
				{				
					// Use the strongly typed property
					switch (name)
					{							
						case "CustomerTypeID": this.str.CustomerTypeID = (string)value; break;							
						case "CustomerDesc": this.str.CustomerDesc = (string)value; break;
					}
				}
				else
				{
					switch (name)
					{	
					
						default:
							break;
					}
				}
			}
			else if(this.Row.Table.Columns.Contains(name))
			{
				this.Row[name] = value;
			}
			else
			{
				throw new Exception("SetProperty Error: '" + name + "' not found");
			}
		}
		
		
		/// <summary>
		/// Maps to CustomerDemographics.CustomerTypeID
		/// </summary>
		virtual public System.String CustomerTypeID
		{
			get
			{
				return base.GetSystemString(CustomerDemographicMetadata.ColumnNames.CustomerTypeID);
			}
			
			set
			{
				if(base.SetSystemString(CustomerDemographicMetadata.ColumnNames.CustomerTypeID, value))
				{
					
					this.MarkFieldAsModified(CustomerDemographicMetadata.ColumnNames.CustomerTypeID);
					if (PropertyChanged != null)
					{
						PropertyChanged(this, new PropertyChangedEventArgs(CustomerDemographicMetadata.PropertyNames.CustomerTypeID));
					}
				}
			}
		}
		
		/// <summary>
		/// Maps to CustomerDemographics.CustomerDesc
		/// </summary>
		virtual public System.String CustomerDesc
		{
			get
			{
				return base.GetSystemString(CustomerDemographicMetadata.ColumnNames.CustomerDesc);
			}
			
			set
			{
				if(base.SetSystemString(CustomerDemographicMetadata.ColumnNames.CustomerDesc, value))
				{
					
					this.MarkFieldAsModified(CustomerDemographicMetadata.ColumnNames.CustomerDesc);
					if (PropertyChanged != null)
					{
						PropertyChanged(this, new PropertyChangedEventArgs(CustomerDemographicMetadata.PropertyNames.CustomerDesc));
					}
				}
			}
		}
		
		#endregion	

		#region String Properties

		[BrowsableAttribute( false )]		
		public esStrings str
		{
			get
			{
				if (esstrings == null)
				{
					esstrings = new esStrings(this);
				}
				return esstrings;
			}
		}


		[Serializable]
		[GeneratedCode]
		sealed public class esStrings
		{
			public esStrings(esCustomerDemographic entity)
			{
				this.entity = entity;
			}
			
	
			public System.String CustomerTypeID
			{
				get
				{
					System.String data = entity.CustomerTypeID;
					return (data == null) ? String.Empty : Convert.ToString(data);
				}

				set
				{
					if (value == null || value.Length == 0) entity.CustomerTypeID = null;
					else entity.CustomerTypeID = Convert.ToString(value);
				}
			}
		  	
			public System.String CustomerDesc
			{
				get
				{
					System.String data = entity.CustomerDesc;
					return (data == null) ? String.Empty : Convert.ToString(data);
				}

				set
				{
					if (value == null || value.Length == 0) entity.CustomerDesc = null;
					else entity.CustomerDesc = Convert.ToString(value);
				}
			}
		  

			private esCustomerDemographic entity;
		}
		#endregion

		#region Query Logic
		protected void InitQuery(esCustomerDemographicQuery query)
		{
			query.OnLoadEvent += new esDynamicQuery.QueryLoadedDelegate(OnQueryLoaded);
			query.es.Connection = ((IEntity)this).Connection;
		}

		protected bool OnQueryLoaded(DataTable table)
		{
			bool dataFound = this.PopulateEntity(table);

			if (this.RowCount > 1)
			{
				throw new Exception("esCustomerDemographic can only hold one record of data");
			}

			return dataFound;
		}
		#endregion
		
		[NonSerialized]
		private esStrings esstrings;
	}


	
	/// <summary>
	/// Hierarchical for the 'CustomerDemographics' table
	/// </summary>
	public partial class CustomerDemographic : esCustomerDemographic
	{
		#region UpToCustomersCollection - Many To Many
		/// <summary>
		/// Many to Many
		/// Foreign Key Name - FK_CustomerCustomerDemo
		/// </summary>

		[Browsable(false)]
		[Bindable(false)]
		[XmlIgnore]
		[GeneratedCode]
		public CustomerCollection UpToCustomersCollection
		{
			[GeneratedCode]
			get
			{
				if(this._UpToCustomersCollection == null)
				{
					this._UpToCustomersCollection = new CustomerCollection();
					this._UpToCustomersCollection.es.Connection.Name = this.es.Connection.Name;
					this.SetPostSave("UpToCustomersCollection", this._UpToCustomersCollection);
					this._UpToCustomersCollection.ManyToManyCustomerDemographicsCollection(this.CustomerTypeID);
				}

				return this._UpToCustomersCollection;
			}
		}

		/// <summary>
		/// Many to Many Associate
		/// Foreign Key Name - FK_CustomerCustomerDemo
		/// </summary>
		[GeneratedCode]
		public void AssociateCustomersCollection(Customer entity)
		{
			if (this._CustomerCustomerDemoCollection == null)
			{
				this._CustomerCustomerDemoCollection = new CustomerCustomerDemoCollection();
				this._CustomerCustomerDemoCollection.es.Connection.Name = this.es.Connection.Name;
				this.SetPostSave("CustomerCustomerDemoCollection", this._CustomerCustomerDemoCollection);
			}

			CustomerCustomerDemo obj = this._CustomerCustomerDemoCollection.AddNew();
			obj.CustomerTypeID = this.CustomerTypeID;
			obj.CustomerID = entity.CustomerID;
		}

		/// <summary>
		/// Many to Many Dissociate
		/// Foreign Key Name - FK_CustomerCustomerDemo
		/// </summary>
		[GeneratedCode]
		public void DissociateCustomersCollection(Customer entity)
		{
			if (this._CustomerCustomerDemoCollection == null)
			{
				this._CustomerCustomerDemoCollection = new CustomerCustomerDemoCollection();
				this._CustomerCustomerDemoCollection.es.Connection.Name = this.es.Connection.Name;
				this.SetPostSave("CustomerCustomerDemoCollection", this._CustomerCustomerDemoCollection);
			}

			CustomerCustomerDemo obj = this._CustomerCustomerDemoCollection.AddNew();
			obj.CustomerTypeID = this.CustomerTypeID;
			obj.CustomerID = entity.CustomerID;
			obj.AcceptChanges();
			obj.MarkAsDeleted();
		}

		[GeneratedCode]
		private CustomerCollection _UpToCustomersCollection;
		[GeneratedCode]
		private CustomerCustomerDemoCollection _CustomerCustomerDemoCollection;
		#endregion

		#region CustomerCustomerDemoByCustomerTypeID - Zero To Many
		/// <summary>
		/// Zero to Many
		/// Foreign Key Name - FK_CustomerCustomerDemo
		/// </summary>

		[Browsable(false)]
		[Bindable(false)]
		[XmlIgnore]
		[GeneratedCode]
		public CustomerCustomerDemoCollection CustomerCustomerDemoByCustomerTypeID
		{
			[GeneratedCode]
			get
			{
				if(this._CustomerCustomerDemoByCustomerTypeID == null)
				{
					this._CustomerCustomerDemoByCustomerTypeID = new CustomerCustomerDemoCollection();
					this._CustomerCustomerDemoByCustomerTypeID.es.Connection.Name = this.es.Connection.Name;
					this.SetPostSave("CustomerCustomerDemoByCustomerTypeID", this._CustomerCustomerDemoByCustomerTypeID);
				
					if(this.CustomerTypeID != null)
					{
						this._CustomerCustomerDemoByCustomerTypeID.Query.Where(this._CustomerCustomerDemoByCustomerTypeID.Query.CustomerTypeID == this.CustomerTypeID);
						this._CustomerCustomerDemoByCustomerTypeID.Query.Load();

						// Auto-hookup Foreign Keys
						this._CustomerCustomerDemoByCustomerTypeID.fks.Add(CustomerCustomerDemoMetadata.ColumnNames.CustomerTypeID, this.CustomerTypeID);
					}
				}

				return this._CustomerCustomerDemoByCustomerTypeID;
			}
		}

		[GeneratedCode]
		private CustomerCustomerDemoCollection _CustomerCustomerDemoByCustomerTypeID;
		#endregion

		/// <summary>
		/// Hierarchical method for retrieving AutoIncrementing keys
		/// during PreSave.
		/// </summary>
		[GeneratedCode]
		protected override void ApplyPreSaveKeys()
		{
		}
		
		/// <summary>
		/// Hierarchical method for retrieving AutoIncrementing keys
		/// during PostSave.
		/// </summary>
		[GeneratedCode]
		protected override void ApplyPostSaveKeys()
		{
		}
		
		/// <summary>
		/// Hierarchical method for retrieving AutoIncrementing keys
		/// during PostOneToOneSave.
		/// </summary>
		[GeneratedCode]
		protected override void ApplyPostOneSaveKeys()
		{
		}
	}
	
	/// <summary>
	/// Hierarchical for the 'CustomerDemographics' table
	/// </summary>
	public partial class CustomerDemographicCollection : esCustomerDemographicCollection
	{
		#region ManyToManyCustomersCollection
		/// <summary>
		/// Hierarchical method for constructing a Many to Many JOIN
		/// </summary>
		[GeneratedCode]
		public bool ManyToManyCustomersCollection(System.String CustomerID)
		{
			esParameters parms = new esParameters();
			parms.Add("CustomerID", CustomerID);
	
			return base.Load( esQueryType.ManyToMany, 
				"CustomerDemographics,CustomerCustomerDemo|CustomerTypeID,CustomerTypeID|CustomerID",	parms);
		}
		#endregion
	}



	[Serializable]
	[GeneratedCode]
	abstract public class esCustomerDemographicQuery : esDynamicQuery
	{
		override protected IMetadata Meta
		{
			get
			{
				return CustomerDemographicMetadata.Meta();
			}
		}	
		

		public esQueryItem CustomerTypeID
		{
			get
			{
				return new esQueryItem(this, CustomerDemographicMetadata.ColumnNames.CustomerTypeID);
			}
		} 
		
		public esQueryItem CustomerDesc
		{
			get
			{
				return new esQueryItem(this, CustomerDemographicMetadata.ColumnNames.CustomerDesc);
			}
		} 
		
	}
	


	[Serializable]
	[XmlType("CustomerDemographicCollection")]
	public partial class CustomerDemographicCollection : esCustomerDemographicCollection, IEnumerable<CustomerDemographic>
	{
		[GeneratedCode]
		public CustomerDemographicCollection()
		{

		}	

		[GeneratedCode]		
		public static implicit operator List<CustomerDemographic>(CustomerDemographicCollection coll)
		{
			List<CustomerDemographic> list = new List<CustomerDemographic>();

			foreach (CustomerDemographic emp in coll)
			{
				list.Add(emp);
			}

			return list;
		}		
		
		#region Housekeeping methods
		[GeneratedCode]
		override protected IMetadata Meta
		{
			[GeneratedCode]
			get
			{
				return  CustomerDemographicMetadata.Meta();
			}
		}	

		[GeneratedCode]
		override protected esDynamicQuery GetDynamicQuery()
		{
			if (this.query == null)
			{
				this.query = new CustomerDemographicQuery();
				this.InitQuery(query);
			}
			return this.query;
		}
		
		[GeneratedCode]
		override protected esEntity CreateEntityForCollection(DataRow row)
		{
			return new CustomerDemographic(row);
		}

		[GeneratedCode]
		override protected esEntity CreateEntity()
		{
			return new CustomerDemographic();
		}
		
			
		#endregion


		[BrowsableAttribute( false )]
		[GeneratedCode]
		public CustomerDemographicQuery Query
		{
			[GeneratedCode]
			get
			{
				if (this.query == null)
				{
					this.query = new CustomerDemographicQuery();
					base.InitQuery(this.query);
				}

				return this.query;
			}
		}

		[GeneratedCode]
		public void QueryReset()
		{
			this.query = null;
		}

		[GeneratedCode]
		public CustomerDemographic AddNew()
		{
			CustomerDemographic entity = base.AddNewEntity() as CustomerDemographic;
			
			return entity;		
		}

		[GeneratedCode]
		public CustomerDemographic FindByPrimaryKey(System.String customerTypeID)
		{
			return base.FindByPrimaryKey(customerTypeID) as CustomerDemographic;
		}


		#region IEnumerable<CustomerDemographic> Members

		[GeneratedCode]
		IEnumerator<CustomerDemographic> IEnumerable<CustomerDemographic>.GetEnumerator()
		{
			System.Collections.IEnumerable enumer = this as System.Collections.IEnumerable;
			System.Collections.IEnumerator iterator = enumer.GetEnumerator();

			while(iterator.MoveNext())
			{
				yield return iterator.Current as CustomerDemographic;
			}
		}

		#endregion
		
		[GeneratedCode]
		private CustomerDemographicQuery query;
	}
	
	




	
	/// <summary>
	/// Encapsulates the 'CustomerDemographics' table
	/// </summary>

	[Serializable]
	public partial class CustomerDemographic : esCustomerDemographic
	{
		[GeneratedCode]	
		public CustomerDemographic()
		{

		}	

		[GeneratedCode]	
		public CustomerDemographic(DataRow row)
			: base(row)
		{

		}
		
		#region Housekeeping methods
		[GeneratedCode]
		override protected IMetadata Meta
		{
			[GeneratedCode]
			get
			{
				return CustomerDemographicMetadata.Meta();
			}
		}

		[GeneratedCode]
		override protected esCustomerDemographicQuery GetDynamicQuery()
		{
			if (this.query == null)
			{
				this.query = new CustomerDemographicQuery();
				this.InitQuery(query);
			}
			return this.query;
		}
		#endregion


		[BrowsableAttribute( false )]
		[GeneratedCode]
		public CustomerDemographicQuery Query
		{
			[GeneratedCode]
			get
			{
				if (this.query == null)
				{
					this.query = new CustomerDemographicQuery();
					base.InitQuery(this.query);
				}

				return this.query;
			}
		}

		[GeneratedCode]
		public void QueryReset()
		{
			this.query = null;
		}

		[GeneratedCode]
		private CustomerDemographicQuery query;
	}
	


	[Serializable]
	[GeneratedCode]
	public partial class CustomerDemographicQuery : esCustomerDemographicQuery
	{
		public CustomerDemographicQuery()
		{

		}		

	}
	


	[Serializable]
	[GeneratedCode]
	public partial class CustomerDemographicMetadata : esMetadata, IMetadata
	{
		#region Protected Constructor
		protected CustomerDemographicMetadata()
		{
			_columns = new esColumnMetadataCollection();
			esColumnMetadata c;

			c = new esColumnMetadata(CustomerDemographicMetadata.ColumnNames.CustomerTypeID, 0, Type.GetType("System.String"));	
			c.PropertyName = CustomerDemographicMetadata.PropertyNames.CustomerTypeID;
			c.IsInPrimaryKey = true;
			c.CharacterMaxLength = 10;
			_columns.Add(c); 
				
			c = new esColumnMetadata(CustomerDemographicMetadata.ColumnNames.CustomerDesc, 1, Type.GetType("System.String"));	
			c.PropertyName = CustomerDemographicMetadata.PropertyNames.CustomerDesc;
			c.CharacterMaxLength = 1073741823;
			c.IsNullable = true;
			_columns.Add(c); 
				
		}
		#endregion

		static public CustomerDemographicMetadata Meta()
		{
			return meta;
		}	
		
		public Guid DataID
		{
			get { return base._dataID; }
		}	
		
		public bool MultiProviderMode
		{
			get { return false; }
		}		

		public esColumnMetadataCollection Columns
		{
			get	{ return base._columns; }
		}
		
		#region ColumnNames
		[GeneratedCode]
		public class ColumnNames
		{ 
			 public const string CustomerTypeID = "CustomerTypeID";
			 public const string CustomerDesc = "CustomerDesc";
		}
		#endregion	
		
		#region PropertyNames
		[GeneratedCode]
		public class PropertyNames
		{ 
			 public const string CustomerTypeID = "CustomerTypeID";
			 public const string CustomerDesc = "CustomerDesc";
		}
		#endregion	

		public esProviderSpecificMetadata GetProviderMetadata(string mapName)
		{
			MapToMeta mapMethod = mapDelegates[mapName];

			if (mapMethod != null)
				return mapMethod(mapName);
			else
				return null;
		}
		
		#region MAP esDefault
		
		static private int RegisterDelegateesDefault()
		{
			// This is only executed once per the life of the application
            if(CustomerDemographicMetadata.mapDelegates == null)
            {
                CustomerDemographicMetadata.mapDelegates = new Dictionary<string,MapToMeta>();
            }

            if (CustomerDemographicMetadata.meta == null)
            {
                CustomerDemographicMetadata.meta = new CustomerDemographicMetadata();
            }
			
			mapDelegates.Add("esDefault", new MapToMeta(meta.esDefault));
			return 0;
		}			

		private esProviderSpecificMetadata esDefault(string mapName)
		{
			if(!_providerMetadataMaps.ContainsKey(mapName))
			{
				esProviderSpecificMetadata meta = new esProviderSpecificMetadata();
				
				meta.AddTypeMap("CustomerTypeID", new esTypeMap("nchar", "System.String"));
				meta.AddTypeMap("CustomerDesc", new esTypeMap("ntext", "System.String"));
			
				
				meta.Schema = "dbo";
				
				meta.Source = "CustomerDemographics";
				meta.Destination = "CustomerDemographics";
				
				
				meta.spInsert = "proc_CustomerDemographicsInsert";				
				meta.spUpdate = "proc_CustomerDemographicsUpdate";		
				meta.spDelete = "proc_CustomerDemographicsDelete";
				meta.spLoadAll = "proc_CustomerDemographicsLoadAll";
				meta.spLoadByPrimaryKey = "proc_CustomerDemographicsLoadByPrimaryKey";
			  
				
				this._providerMetadataMaps["esDefault"] = meta;
			}
			
			return this._providerMetadataMaps["esDefault"];
		}

		#endregion

		static private CustomerDemographicMetadata meta;
		static protected Dictionary<string, MapToMeta> mapDelegates;
		static private int _esDefault = RegisterDelegateesDefault();
	}
}

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
Software Developer VirtualScopics, Inc
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions