Click here to Skip to main content
15,885,537 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 51K   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:30 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 esCategoryCollection : esEntityCollection, INotifyCollectionChanged
	{
		public esCategoryCollection()
		{

		}
		
		public event NotifyCollectionChangedEventHandler CollectionChanged;
		
		protected override string GetCollectionName()
		{
			return "CategoryCollection";
		}
		
		#region Query Logic
		protected void InitQuery(esCategoryQuery 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 Category DetachEntity(Category entity)
		{
			return base.DetachEntity(entity) as Category;
		}
		
		virtual public Category AttachEntity(Category entity)
		{
			return base.AttachEntity(entity) as Category;
		}
		
		virtual public void Combine(CategoryCollection collection)
		{
            base.Combine(collection);
        }
		
        new public Category this[int index]
        {
            get
            {
                return base[index] as Category;
            }
        }		
	}
	


	[Serializable]
	[GeneratedCode]
	abstract public class esCategory : esEntity, INotifyPropertyChanged
	{
		virtual protected esCategoryQuery GetDynamicQuery()
		{
			return null;
		}
		
		public esCategory()
		{
		}
	
		public esCategory(DataRow row)
			: base(row)
		{
		}
		
		#region LoadByPrimaryKey
		public virtual bool LoadByPrimaryKey(System.Int32 categoryID)
		{
			if(this.es.Connection.SqlAccessType == esSqlAccessType.DynamicSQL)
				return LoadByPrimaryKeyDynamic(categoryID);
			else
				return LoadByPrimaryKeyStoredProcedure(categoryID);
		}
	
		/// <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.Int32 categoryID)
		{
			if (sqlAccessType == esSqlAccessType.DynamicSQL)
				return LoadByPrimaryKeyDynamic(categoryID);
			else
				return LoadByPrimaryKeyStoredProcedure(categoryID);
		}
	
		private bool LoadByPrimaryKeyDynamic(System.Int32 categoryID)
		{
			esCategoryQuery query = this.GetDynamicQuery();
			query.Where(query.CategoryID == categoryID);
			return query.Load();
		}
	
		private bool LoadByPrimaryKeyStoredProcedure(System.Int32 categoryID)
		{
			EntitySpaces.Interfaces.esParameters parms = new EntitySpaces.Interfaces.esParameters();
			parms.Add("CategoryID",categoryID);
			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 "CategoryID": this.str.CategoryID = (string)value; break;							
						case "CategoryName": this.str.CategoryName = (string)value; break;							
						case "Description": this.str.Description = (string)value; break;
					}
				}
				else
				{
					switch (name)
					{	
						case "CategoryID":
						
							if (value == null || value.GetType().ToString() == "System.Int32")
								this.CategoryID = (System.Int32?)value;
							break;
						
						case "Picture":
						
							if (value == null || value.GetType().ToString() == "System.Byte[]")
								this.Picture = (System.Byte[])value;
							break;
						
					
						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 Categories.CategoryID
		/// </summary>
		virtual public System.Int32? CategoryID
		{
			get
			{
				return base.GetSystemInt32(CategoryMetadata.ColumnNames.CategoryID);
			}
			
			set
			{
				if(base.SetSystemInt32(CategoryMetadata.ColumnNames.CategoryID, value))
				{
					
					this.MarkFieldAsModified(CategoryMetadata.ColumnNames.CategoryID);
					if (PropertyChanged != null)
					{
						PropertyChanged(this, new PropertyChangedEventArgs(CategoryMetadata.PropertyNames.CategoryID));
					}
				}
			}
		}
		
		/// <summary>
		/// Maps to Categories.CategoryName
		/// </summary>
		virtual public System.String CategoryName
		{
			get
			{
				return base.GetSystemString(CategoryMetadata.ColumnNames.CategoryName);
			}
			
			set
			{
				if(base.SetSystemString(CategoryMetadata.ColumnNames.CategoryName, value))
				{
					
					this.MarkFieldAsModified(CategoryMetadata.ColumnNames.CategoryName);
					if (PropertyChanged != null)
					{
						PropertyChanged(this, new PropertyChangedEventArgs(CategoryMetadata.PropertyNames.CategoryName));
					}
				}
			}
		}
		
		/// <summary>
		/// Maps to Categories.Description
		/// </summary>
		virtual public System.String Description
		{
			get
			{
				return base.GetSystemString(CategoryMetadata.ColumnNames.Description);
			}
			
			set
			{
				if(base.SetSystemString(CategoryMetadata.ColumnNames.Description, value))
				{
					
					this.MarkFieldAsModified(CategoryMetadata.ColumnNames.Description);
					if (PropertyChanged != null)
					{
						PropertyChanged(this, new PropertyChangedEventArgs(CategoryMetadata.PropertyNames.Description));
					}
				}
			}
		}
		
		/// <summary>
		/// Maps to Categories.Picture
		/// </summary>
		virtual public System.Byte[] Picture
		{
			get
			{
				return base.GetSystemByteArray(CategoryMetadata.ColumnNames.Picture);
			}
			
			set
			{
				if(base.SetSystemByteArray(CategoryMetadata.ColumnNames.Picture, value))
				{
					
					this.MarkFieldAsModified(CategoryMetadata.ColumnNames.Picture);
					if (PropertyChanged != null)
					{
						PropertyChanged(this, new PropertyChangedEventArgs(CategoryMetadata.PropertyNames.Picture));
					}
				}
			}
		}
		
		#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(esCategory entity)
			{
				this.entity = entity;
			}
			
	
			public System.String CategoryID
			{
				get
				{
					System.Int32? data = entity.CategoryID;
					return (data == null) ? String.Empty : Convert.ToString(data);
				}

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

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

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

			private esCategory entity;
		}
		#endregion

		#region Query Logic
		protected void InitQuery(esCategoryQuery 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("esCategory can only hold one record of data");
			}

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


	
	/// <summary>
	/// Hierarchical for the 'Categories' table
	/// </summary>
	public partial class Category : esCategory
	{
		#region ProductsByCategoryID - Zero To Many
		/// <summary>
		/// Zero to Many
		/// Foreign Key Name - FK_Products_Categories
		/// </summary>

		[Browsable(false)]
		[Bindable(false)]
		[XmlIgnore]
		[GeneratedCode]
		public ProductCollection ProductsByCategoryID
		{
			[GeneratedCode]
			get
			{
				if(this._ProductsByCategoryID == null)
				{
					this._ProductsByCategoryID = new ProductCollection();
					this._ProductsByCategoryID.es.Connection.Name = this.es.Connection.Name;
					this.SetPostSave("ProductsByCategoryID", this._ProductsByCategoryID);
				
					if(this.CategoryID != null)
					{
						this._ProductsByCategoryID.Query.Where(this._ProductsByCategoryID.Query.CategoryID == this.CategoryID);
						this._ProductsByCategoryID.Query.Load();

						// Auto-hookup Foreign Keys
						this._ProductsByCategoryID.fks.Add(ProductMetadata.ColumnNames.CategoryID, this.CategoryID);
					}
				}

				return this._ProductsByCategoryID;
			}
		}

		[GeneratedCode]
		private ProductCollection _ProductsByCategoryID;
		#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()
		{
			if(this._ProductsByCategoryID != null)
			{
				foreach(Product obj in this._ProductsByCategoryID)
				{
					if(obj.es.IsAdded)
					{
						obj.CategoryID = this.CategoryID;
					}
				}
			}
		}
		
		/// <summary>
		/// Hierarchical method for retrieving AutoIncrementing keys
		/// during PostOneToOneSave.
		/// </summary>
		[GeneratedCode]
		protected override void ApplyPostOneSaveKeys()
		{
		}
	}


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

		public esQueryItem CategoryID
		{
			get
			{
				return new esQueryItem(this, CategoryMetadata.ColumnNames.CategoryID);
			}
		} 
		
		public esQueryItem CategoryName
		{
			get
			{
				return new esQueryItem(this, CategoryMetadata.ColumnNames.CategoryName);
			}
		} 
		
		public esQueryItem Description
		{
			get
			{
				return new esQueryItem(this, CategoryMetadata.ColumnNames.Description);
			}
		} 
		
		public esQueryItem Picture
		{
			get
			{
				return new esQueryItem(this, CategoryMetadata.ColumnNames.Picture);
			}
		} 
		
	}
	


	[Serializable]
	[XmlType("CategoryCollection")]
	public partial class CategoryCollection : esCategoryCollection, IEnumerable<Category>
	{
		[GeneratedCode]
		public CategoryCollection()
		{

		}	

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

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

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

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

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


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

				return this.query;
			}
		}

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

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

		[GeneratedCode]
		public Category FindByPrimaryKey(System.Int32 categoryID)
		{
			return base.FindByPrimaryKey(categoryID) as Category;
		}


		#region IEnumerable<Category> Members

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

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

		#endregion
		
		[GeneratedCode]
		private CategoryQuery query;
	}
	
	



	/// <summary>
	/// Value enumeration for Categories table.
	/// </summary>
	public enum Categories
	{
		Beverages = 1,
		Condiments = 2,
		Confections = 3,
		Dairy_Products = 4,
		Grains_Cereals = 5,
		Meat_Poultry = 6,
		Produce = 7,
		Seafood = 8
	};


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

	[Serializable]
	public partial class Category : esCategory
	{
		[GeneratedCode]	
		public Category()
		{

		}	

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

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

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


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

				return this.query;
			}
		}

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

		[GeneratedCode]
		private CategoryQuery query;
	}
	


	[Serializable]
	[GeneratedCode]
	public partial class CategoryQuery : esCategoryQuery
	{
		public CategoryQuery()
		{

		}		

	}
	


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

			c = new esColumnMetadata(CategoryMetadata.ColumnNames.CategoryID, 0, Type.GetType("System.Int32"));	
			c.PropertyName = CategoryMetadata.PropertyNames.CategoryID;
			c.IsInPrimaryKey = true;
			c.IsAutoIncrement = true;
			c.NumericPrecision = 10;
			_columns.Add(c); 
				
			c = new esColumnMetadata(CategoryMetadata.ColumnNames.CategoryName, 1, Type.GetType("System.String"));	
			c.PropertyName = CategoryMetadata.PropertyNames.CategoryName;
			c.CharacterMaxLength = 15;
			_columns.Add(c); 
				
			c = new esColumnMetadata(CategoryMetadata.ColumnNames.Description, 2, Type.GetType("System.String"));	
			c.PropertyName = CategoryMetadata.PropertyNames.Description;
			c.CharacterMaxLength = 1073741823;
			c.IsNullable = true;
			_columns.Add(c); 
				
			c = new esColumnMetadata(CategoryMetadata.ColumnNames.Picture, 3, Type.GetType("System.Byte[]"));	
			c.PropertyName = CategoryMetadata.PropertyNames.Picture;
			c.CharacterMaxLength = 2147483647;
			c.IsNullable = true;
			_columns.Add(c); 
				
		}
		#endregion

		static public CategoryMetadata 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 CategoryID = "CategoryID";
			 public const string CategoryName = "CategoryName";
			 public const string Description = "Description";
			 public const string Picture = "Picture";
		}
		#endregion	
		
		#region PropertyNames
		[GeneratedCode]
		public class PropertyNames
		{ 
			 public const string CategoryID = "CategoryID";
			 public const string CategoryName = "CategoryName";
			 public const string Description = "Description";
			 public const string Picture = "Picture";
		}
		#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(CategoryMetadata.mapDelegates == null)
            {
                CategoryMetadata.mapDelegates = new Dictionary<string,MapToMeta>();
            }

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

		private esProviderSpecificMetadata esDefault(string mapName)
		{
			if(!_providerMetadataMaps.ContainsKey(mapName))
			{
				esProviderSpecificMetadata meta = new esProviderSpecificMetadata();
				
				meta.AddTypeMap("CategoryID", new esTypeMap("int", "System.Int32"));
				meta.AddTypeMap("CategoryName", new esTypeMap("nvarchar", "System.String"));
				meta.AddTypeMap("Description", new esTypeMap("ntext", "System.String"));
				meta.AddTypeMap("Picture", new esTypeMap("image", "System.Byte[]"));
			
				
				meta.Schema = "dbo";
				
				meta.Source = "Categories";
				meta.Destination = "Categories";
				
				
				meta.spInsert = "proc_CategoriesInsert";				
				meta.spUpdate = "proc_CategoriesUpdate";		
				meta.spDelete = "proc_CategoriesDelete";
				meta.spLoadAll = "proc_CategoriesLoadAll";
				meta.spLoadByPrimaryKey = "proc_CategoriesLoadByPrimaryKey";
			  
				
				this._providerMetadataMaps["esDefault"] = meta;
			}
			
			return this._providerMetadataMaps["esDefault"];
		}

		#endregion

		static private CategoryMetadata 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