Compare commits

...

48 Commits

Author SHA1 Message Date
Railz c65cffd2e7 Set version to 1.5.3 5 years ago
Railz 3356a3fa89 Added documentation for overloads
Added overloading methods for easier access
5 years ago
Railz 8c82d535f1 Added check if FillObject has missing attributes in class 5 years ago
Railz 56d8cea635 Removed type-conversion 5 years ago
Railz 64418fb9e9 Added conversion fo specific types to match correct type before filling 5 years ago
Railz c7b9f67004 Fixed List-detection 5 years ago
Railz d3d0ed7378 Fixed stackOverFlow when 2 classes depend on each other 5 years ago
Railz 7365ffbee6 Fixed init of DbReverseForeignObject generic list detection and extraction 5 years ago
Railz 3784108a4e Fixed init of DbIntermediateForeignObject 5 years ago
Railz 7e56187733 FillObject: Check if keys are Dbnull, so not set
ResolveForeignKeys: Check if key is set
5 years ago
Railz ef73a51ab5 Fixed Init stackOverFlowException for recursive objects 5 years ago
Railz d86e231bda Fixed ResolveForeignKeys:
Changed generic creation to reflective generation of new object
Fixed loading himself
5 years ago
Railz 178c92383b Added Insert, Update and Insert ClassActions 5 years ago
Railz 2f243e6ccf Catching known errors that may occur whilst resolving unknown object 6 years ago
Railz 1c2c8f6e76 Set verion to 1.5.21 6 years ago
Railz 5da5d455b9 Fixed GetByPrimaryKey with only primaryKeyValue throwing error because of null-key 6 years ago
Railz 3a0af04b1c Added DbIntermediateForeignObject and resolver
Set version to 1.5.20
6 years ago
Railz 4f7495ea68 Added fix for recursion bubbling back due to not set subAttribute 6 years ago
Railz 111b3bf7ce Added DbReverseForeignObject
Removed method SqlSerialise(DateTime ...)
6 years ago
Railz aca99302dd Set version to 1.5.15 6 years ago
Railz 7317503759 Added GetListWithQuery 6 years ago
Railz 75f4709db1 Added check if ResolveByPrimaryKey returned any results from database. 6 years ago
Railz 0d07d82ff5 Added table-name remover to matching-system of FillObject 6 years ago
Railz b6bc82a766 Set version to 1.5.12 6 years ago
Railz 3e8427c4c0 Fixed Guid casting to String (dunno?) 6 years ago
Railz 8816110211 Improved Exception messages (variables)
CLassAction: Added GetList
Set Version to 1.5.11
6 years ago
Alexander B 40936fafcd Set version to 1.5.9 6 years ago
Alexander B 800941d59c Implemented:
QueryBuilder.SelectWithWhere()
ClassAction.GetListWithWhere()
6 years ago
Railz 64c8711754 Set version 6 years ago
Railz ad3c1da0cd Fixes:
- Fields not matching
- FieldType being lookedUp wrong
- dictionary-access-violation
- guid saved as string not casting
- InsertQuery built wrong
6 years ago
Railz ba0646f27c Set version to 1.5.7 6 years ago
Railz 76922a4039 Changed cache-check to dictionary
> Fixed bug, not restoring cache
6 years ago
Railz e3869b26c3 removed inner Exception 6 years ago
Alexander B be7277fada Set version 1.5.6 6 years ago
Alexander B b8218fbacd Added InsertAttributesByObject 6 years ago
Alexander B 253f63dfac Added InsertAttributes to generate insert-statements 6 years ago
Alexander B d6337ef591 Ser version 6 years ago
Alexander B 1253a935b7 Added ResolveByPrimaryKey to resolve an object with set primaryKey/s 6 years ago
Railz 2d4a4d5f7e Changed DbForeignObject no longer needing the Type 6 years ago
Railz 85495af97f Added DbForeignObject for automatic resolving
Added Init() to initialise necessary classes
Changed structure and added a BaseAttribute
Fixed occuring errors to match new system
6 years ago
Railz 9253d77236 Fixed GetByPrimaryKey not having any form to pass primaryKey-data
Set version to 1.4.1
6 years ago
Railz ef7ac54e36 Set version 6 years ago
Railz 83dc8d6045 Added foreignKeyFieldName for foreignKeys
Added ResolveForeignKeys to ClassActions
Changed ResolveByPrimaryKey to GetByPrimaryKey
Added todo's
6 years ago
Railz ff6fb08a08 Fixed missing convertion 6 years ago
Railz d2900f364d Set version 6 years ago
Railz b014c2f392 Added Method to convert classField-names to according dbAttributes
Added convert in GetListByAttribute
6 years ago
Railz 0ad7221680 Set version 6 years ago
Railz 36da32f870 Added Select/DeleteByAttribute
Added GetListByAttribute
6 years ago

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace eu.railduction.netcore.dll.Database_Attribute_System.Attributes
{
public class BaseAttribute : Attribute
{
public FieldInfo parentField;
public DbObject classAttribute;
public string _attributeName;
public BaseAttribute()
{
}
}
}

@ -1,15 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace eu.railduction.netcore.dll.Database_Attribute_System.Attributes
{
[AttributeUsage(AttributeTargets.Field, Inherited = false, AllowMultiple = false)]
public class DbAttribute : Attribute
public class DbAttribute : BaseAttribute
{
public string _attributeName;
/// <summary>
/// Marks variable as database-attribute
/// </summary>
@ -18,5 +17,13 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System.Attributes
{
this._attributeName = attributeName;
}
public void Init(FieldInfo fi, DbObject classAttribute)
{
this.parentField = fi;
this.classAttribute = classAttribute;
this._attributeName = this._attributeName ?? fi.Name; // If no alternative attribute-name is specified, use the property-name
}
}
}

@ -1,25 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace eu.railduction.netcore.dll.Database_Attribute_System.Attributes
{
[AttributeUsage(AttributeTargets.Field, Inherited = false, AllowMultiple = false)]
public class DbForeignKey : Attribute
public class DbForeignKey : BaseAttribute
{
public Type _classType;
public string _attributeName;
/// <summary>
/// Marks variable as foreignKey of given class
/// </summary>
/// <param name="classType">Type of class to which this is the ForeignKey</param>
/// <param name="dbAttributeName">Name of database-attribute (case-sensitivity is determined from database-attribute-settings) ['null' if the same as field-name]</param>
public DbForeignKey(Type classType, string attributeName = null)
public DbForeignKey(string attributeName = null)
{
this._classType = classType;
this._attributeName = attributeName;
}
public void Init(FieldInfo fi, DbObject classAttribute)
{
this.parentField = fi;
this.classAttribute = classAttribute;
this._attributeName = this._attributeName ?? fi.Name; // If no alternative attribute-name is specified, use the property-name
}
}
}

@ -1,23 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace eu.railduction.netcore.dll.Database_Attribute_System.Attributes
{
[AttributeUsage(AttributeTargets.Field, Inherited = false, AllowMultiple = false)]
public class DbPrimaryKey : Attribute
public class DbPrimaryKey : BaseAttribute
{
public Type _classType;
public string _attributeName;
/// <summary>
/// Marks variable as primaryKey fo current class
/// </summary>
/// <param name="dbAttributeName">Name of database-attribute (case-sensitivity is determined from database-attribute-settings) ['null' if the same as field-name]</param>
public DbPrimaryKey(string attributeName = null)
{
this._attributeName = attributeName;
this._attributeName = attributeName; // Todo: Automatic resolving of name if it is null (?)
}
public void Init(FieldInfo fi, DbObject classAttribute)
{
this.parentField = fi;
this.classAttribute = classAttribute;
this._attributeName = this._attributeName ?? fi.Name; // If no alternative attribute-name is specified, use the property-name
}
}
}

@ -0,0 +1,80 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace eu.railduction.netcore.dll.Database_Attribute_System.Attributes
{
[AttributeUsage(AttributeTargets.Field, Inherited = false, AllowMultiple = false)]
public class DbForeignObject : Attribute
{
public Type foreignObjectType;
public string _foreignKeyName;
public DbForeignKey foreignKeyAttribute;
public FieldInfo parentField;
public DbObject classAttribute;
/// <summary>
/// Marks variable as foreign-object of an dbObject
/// </summary>
/// <param name="foreignKeyName">Fieldname of foreignKey associated with the foreignObject</param>
public DbForeignObject(string foreignKeyName = null)
{
this._foreignKeyName = foreignKeyName;
}
public void Init(FieldInfo fi, DbObject classAttribute, DbObject foreignClassAttribute = null)
{
this.parentField = fi;
this.classAttribute = classAttribute;
this.foreignObjectType = fi.FieldType;
// Init foreign-object class
if(foreignClassAttribute == null)
foreignClassAttribute = ClassAction.Init(this.foreignObjectType);
// Check if something is weird
if (foreignClassAttribute.primaryKeyAttributes.Count < 1) throw new InvalidOperationException($"'{foreignClassAttribute.parentClassType.Name}' does not have a primaryKey.");
if (foreignClassAttribute.primaryKeyAttributes.Count > 1) throw new InvalidOperationException($"ForeignObject does not support multiple primaryKeys.");
Type primaryKeyType = foreignClassAttribute.primaryKeyAttributes[0].parentField.GetType(); // Read type of primaryKey in foreignObject-class
foreach(DbForeignKey foreignKey in classAttribute.foreignKeyAttributes) // Search for matching foreignKey
{
if(this._foreignKeyName != null) // If i have a name
{
// check if name matches
if (foreignKey.parentField.Name.ToLower() == this._foreignKeyName.ToLower())
{
if(foreignKey.parentField.GetType() == primaryKeyType)
{
this._foreignKeyName = foreignKey.parentField.Name;
foreignKeyAttribute = foreignKey;
break;
}
else
{
// If a name was specified and the key does not match its an error
throw new InvalidOperationException($"ForeignKey='{this._foreignKeyName}' is typeOf='{foreignKey.parentField.GetType().Name}' but primaryKey of foreignObject-class is typeOf='{primaryKeyType.Name}'.");
}
}
}
else // No name
{
// Check if type matches
if (foreignKey.parentField.GetType() == primaryKeyType)
{
this._foreignKeyName = foreignKey.parentField.Name;
foreignKeyAttribute = foreignKey;
break;
}
}
}
// Check if key-retrieval was successful
if (foreignKeyAttribute == null) throw new InvalidOperationException($"No coresponding foreignKey.");
}
}
}

@ -0,0 +1,78 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace eu.railduction.netcore.dll.Database_Attribute_System.Attributes
{
[AttributeUsage(AttributeTargets.Field, Inherited = false, AllowMultiple = false)]
public class DbIntermediateForeignObject : Attribute
{
public Type foreignObjectType;
public string _intermediateTableName;
public string _keyName;
public string _foreignKeyName;
public DbPrimaryKey foreignPrimaryKeyAttribute;
public FieldInfo parentField;
public DbObject classAttribute;
/// <summary>
/// Marks variable as intermediate-object of an dbObject
/// </summary>
/// <param name="intermediateTableName">Table-name of intermediate-table. Must contain primaryKey of this class & target class</param>
/// <param name="keyName">Fieldname of primaryKey associated with the IntermediateObject on this side [m]:n (null if same as primary key) [Only works with 1 primaryKey]</param>
/// <param name="foreignKeyName">Fieldname of primaryKey associated with the IntermediateObject on the other side m:[n] (null if same as primary key) [Only works with 1 primaryKey]</param>
public DbIntermediateForeignObject(string intermediateTableName, string keyName = null, string foreignKeyName = null)
{
this._intermediateTableName = intermediateTableName;
this._foreignKeyName = foreignKeyName;
}
public void Init(FieldInfo fi, DbObject classAttribute)
{
this.parentField = fi;
this.classAttribute = classAttribute;
this.foreignObjectType = fi.FieldType;
if (classAttribute.primaryKeyAttributes.Count < 1) throw new InvalidOperationException($"'{classAttribute.parentClassType.Name}' does not have a primaryKey.");
if (classAttribute.primaryKeyAttributes.Count > 1) throw new InvalidOperationException($"IntermediateObject does not support multiple primaryKeys.");
// Get primaryKey name if none is set
if (_keyName == null) _keyName = classAttribute.primaryKeyAttributes[0]._attributeName;
if (!(fi.FieldType.IsGenericType && (fi.FieldType.GetGenericTypeDefinition() == typeof(List<>)))) // 1:m
throw new InvalidOperationException($"IntermediateObject has to be typeof(List<T>). Maybe you meant to use DbForeignObject or DbReverseForeignObject for 1:m or 1:1 relations.");
// Check the generic list and get inner-type
Type foreignObjectType = null;
foreach (Type interfaceType in fi.FieldType.GetInterfaces())
{
if (interfaceType.IsGenericType &&
interfaceType.GetGenericTypeDefinition()
== typeof(IList<>))
{
foreignObjectType = fi.FieldType.GetGenericArguments()[0];
break;
}
}
if (foreignObjectType == null) throw new InvalidOperationException("Could not read innter-type of generic-list!");
// Init inner-type class
DbObject foreignClassAttribute = ClassAction.Init(foreignObjectType);
// Check the primaryKey/s
if (foreignClassAttribute.primaryKeyAttributes.Count < 1) throw new InvalidOperationException($"'{foreignClassAttribute.parentClassType.Name}' does not have a primaryKey.");
if (foreignClassAttribute.primaryKeyAttributes.Count > 1) throw new InvalidOperationException($"IntermediateObject does not support multiple primaryKeys. (Found '{foreignClassAttribute.primaryKeyAttributes.Count}' in '{foreignClassAttribute.parentClassType.Name}')");
// Save it
foreignPrimaryKeyAttribute = foreignClassAttribute.primaryKeyAttributes[0];
if (_foreignKeyName == null) _foreignKeyName = foreignPrimaryKeyAttribute._attributeName;
}
}
}

@ -12,13 +12,86 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System.Attributes
{
public string _tableName;
public Type parentClassType;
public ConstructorInfo parentCInfo;
// All childrenAttributes
public List<BaseAttribute> baseAttributes = new List<BaseAttribute>() { };
public List<DbPrimaryKey> primaryKeyAttributes = new List<DbPrimaryKey>() { };
public List<DbAttribute> attributeAttributes = new List<DbAttribute>() { };
public List<DbForeignKey> foreignKeyAttributes = new List<DbForeignKey>() { };
public List<DbForeignObject> foreignObjectAttributes = new List<DbForeignObject>() { };
public List<DbReverseForeignObject> reverseForeignObjectAttributes = new List<DbReverseForeignObject>() { };
public List<DbIntermediateForeignObject> intermediateObjectAttributes = new List<DbIntermediateForeignObject>() { };
/// <summary>
/// Marks variable as database-table
/// </summary>
/// <param name="tableName">Name of database-table (case-sensitivity is determined from database-table-settings) ['null' if the same as class-name]</param>
public DbObject(string tableName = null)
{
this._tableName = tableName;
this._tableName = tableName; // Todo: Automatic resolving of name if it is null (?)
}
public void Init(Type classType)
{
this.parentClassType = classType;
parentCInfo = classType.GetConstructor(Type.EmptyTypes);
this._tableName = this._tableName ?? classType.Name; // If no alternative table-name is specified, use the class-name
// Iterate thru all fields
foreach (System.Reflection.FieldInfo fi in classType.GetRuntimeFields())
{
try
{
// Check if current field is a db-field and initiate it
if (fi.GetCustomAttribute(typeof(DbPrimaryKey), true) is DbPrimaryKey pkey) // PrimaryKey
{
pkey.Init(fi, this);
this.baseAttributes.Add(pkey);
this.primaryKeyAttributes.Add(pkey);
}
else if (fi.GetCustomAttribute(typeof(DbAttribute), true) is DbAttribute att) // Attributes
{
att.Init(fi, this);
this.baseAttributes.Add(att);
this.attributeAttributes.Add(att);
}
else if (fi.GetCustomAttribute(typeof(DbForeignKey), true) is DbForeignKey fkey) // ForeignKeys
{
fkey.Init(fi, this);
this.baseAttributes.Add(fkey);
this.foreignKeyAttributes.Add(fkey);
}
else if (fi.GetCustomAttribute(typeof(DbForeignObject), true) is DbForeignObject fobj) // ForeignObjects
{
if(fi.FieldType == this.parentClassType) // Check if we are referencing ourselfes
fobj.Init(fi, this, this);
else
fobj.Init(fi, this);
this.foreignObjectAttributes.Add(fobj);
}
else if (fi.GetCustomAttribute(typeof(DbReverseForeignObject), true) is DbReverseForeignObject rfobj) // ReverseForeignObjects
{
rfobj.Init(fi, this);
this.reverseForeignObjectAttributes.Add(rfobj);
}
else if (fi.GetCustomAttribute(typeof(DbIntermediateForeignObject), true) is DbIntermediateForeignObject iobj) // ReverseForeignObjects
{
iobj.Init(fi, this);
this.intermediateObjectAttributes.Add(iobj);
}
}
catch(InvalidOperationException ex)
{
throw new InvalidOperationException($"Cannot init foreignObject-field='{fi.Name}' of class='{classType.Name}'.", ex);
}
}
}
}
}

@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace eu.railduction.netcore.dll.Database_Attribute_System.Attributes
{
[AttributeUsage(AttributeTargets.Field, Inherited = false, AllowMultiple = false)]
public class DbReverseForeignObject : Attribute
{
public Type foreignObjectType;
public string _foreignKeyName;
public DbForeignKey foreignKeyAttribute;
public FieldInfo parentField;
public DbObject classAttribute;
/// <summary>
/// Marks variable as reverse-foreign-object of an dbObject
/// </summary>
/// <param name="foreignKeyName">Fieldname of primaryKey associated with the reverseForeignObject (null if same as primary key) [Only works with 1 primaryKey]</param>
public DbReverseForeignObject(string foreignKeyName = null)
{
this._foreignKeyName = foreignKeyName;
}
public void Init(FieldInfo fi, DbObject classAttribute)
{
this.parentField = fi;
this.classAttribute = classAttribute;
this.foreignObjectType = fi.FieldType;
if (classAttribute.primaryKeyAttributes.Count < 1) throw new InvalidOperationException($"'{classAttribute.parentClassType.Name}' does not have a primaryKey.");
if (classAttribute.primaryKeyAttributes.Count > 1) throw new InvalidOperationException($"ReverseForeignObject does not support multiple primaryKeys.");
// Get primaryKey name if none is set
if (_foreignKeyName == null) _foreignKeyName = classAttribute.primaryKeyAttributes[0]._attributeName;
// If its a List, get inner type
if (fi.FieldType.IsGenericType && (fi.FieldType.GetGenericTypeDefinition() == typeof(List<>)))
{
// Check the generic list and get inner-type
foreach (Type interfaceType in fi.FieldType.GetInterfaces())
{
if (interfaceType.IsGenericType &&
interfaceType.GetGenericTypeDefinition()
== typeof(IList<>))
{
foreignObjectType = fi.FieldType.GetGenericArguments()[0];
break;
}
}
if (foreignObjectType == null) throw new InvalidOperationException("Could not read innter-type of generic-list!");
}
// Init inner-type class
DbObject foreignClassAttribute = ClassAction.Init(foreignObjectType);
// Check if my primary-key is set in the foreign-class as foreignKey
DbPrimaryKey primaryKey = classAttribute.primaryKeyAttributes[0];
foreach (DbForeignKey foreignKey in foreignClassAttribute.foreignKeyAttributes)
{
if (primaryKey._attributeName.ToLower() == foreignKey._attributeName.ToLower()) // Name matches
if (primaryKey.parentField.GetType() == foreignKey.parentField.GetType()) // Type matches
{
foreignKeyAttribute = foreignKey;
}
else
// Same name, but wrong type
throw new InvalidOperationException($"ForeignObject='{foreignClassAttribute.parentClassType.Name}' has invalid type foreignKey='{foreignKey.parentField.Name}' for object='{classAttribute.parentClassType.Name}' with primaryKey='{primaryKey.parentField.Name}'.");
}
// No match
if (foreignKeyAttribute == null) throw new InvalidOperationException($"ForeignObject='{foreignClassAttribute.parentClassType.Name}' is missing foreignKey for object='{classAttribute.parentClassType.Name}' with primaryKey='{primaryKey.parentField.Name}'.");
}
}
}

@ -1,4 +1,6 @@
using System;
using eu.railduction.netcore.dll.Database_Attribute_System.Attributes;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
@ -7,6 +9,47 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
{
public class ClassAction
{
private static Dictionary<Type, DbObject> initiatedClassTypes = new Dictionary<Type, DbObject>() { };
/// <summary>
/// Initiates the attribute-system and preloads all necessary information<para/>
/// INFO: Will initiate necessary foreignObjects recursively!<para/>
/// If an class is already initiated, it will be ignored!
/// </summary>
/// <param name="classType">The classType to preload</param>
/// <returns>DbObject-attribute corresponding to the class</returns>
public static DbObject Init(Type classType)
{
DbObject cachedDbObject;
initiatedClassTypes.TryGetValue(classType, out cachedDbObject);
if (cachedDbObject == null)
{
// Check if given class is marked as dbObject
if (!(classType.GetCustomAttribute(typeof(DbObject), true) is DbObject dbObject)) throw new InvalidOperationException($"Cannot init '{classType.Name}'. Missing Attribute 'DbObject'");
initiatedClassTypes.Add(classType, dbObject); // Set it to the list
dbObject.Init(classType); // Init dbObject
cachedDbObject = dbObject;
}
return cachedDbObject;
}
/// <summary>
/// Fills an given dbObject with given data<para/>
/// Data-attribute-names and class-fieldNames have to match! (non case-sensitive)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="classObject">Given object (marked with Db-attributes)</param>
/// <param name="data">The data</param>
/// <param name="key">Key-name of data</param>
public static void FillObject<T>(T classObject, string key, object data)
{
Dictionary<string, object> dicData = new Dictionary<string, object>();
dicData.Add(key, data);
FillObject<T>(classObject, dicData);
}
/// <summary>
/// Fills an given dbObject with given data<para/>
/// Data-attribute-names and class-fieldNames have to match! (non case-sensitive)
@ -14,79 +57,531 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
/// <typeparam name="T"></typeparam>
/// <param name="classObject">Given object (marked with Db-attributes)</param>
/// <param name="data">The data</param>
/// <param name="runDataLossChecks">This checks if any class-field and data-attribute does not exists in either (Slower)</param>
public static void FillObject<T>(T classObject, Dictionary<string, object> data, bool runDataLossChecks = true)
/// <param name="key">Key-name of data</param>
public static void FillObject<T>(T classObject, Dictionary<string, object> data)
{
Type classType = classObject.GetType();
string tableName = Function.GetDbTableName(classType);
// Read dbObject-attribute
DbObject dbObject = ClassAction.Init(classType);
// Get class-fields
Dictionary<string, FieldInfo> dbFields = Function.ReadDbClassFields(classObject);
// Iterate through data
foreach (KeyValuePair<string, object> data_keySet in data)
{
bool dataMatchFound = false;
if (runDataLossChecks)
// Interate through class-fields
foreach (BaseAttribute baseAttribute in dbObject.baseAttributes)
{
// Check every data-attribute for match in class-fields
foreach (KeyValuePair<string, object> data_keySet in data)
// Remove any leading dots and table-specifiers
string dbAttName = data_keySet.Key;
if (dbAttName.Contains("."))
{
bool isFound = false;
foreach (KeyValuePair<string, FieldInfo> field_keySet in dbFields)
string[] dbAttNameSplit = dbAttName.Split('.'); // Split at the '.'
dbAttName = dbAttNameSplit[dbAttNameSplit.Length - 1]; // Copy the ending text
}
// If its a match, set the value
if (baseAttribute._attributeName.ToLower() == data_keySet.Key.ToLower())
{
object value = data_keySet.Value;
if (!(value is DBNull)) // Check if value is empty
{
if (field_keySet.Key.ToLower() == data_keySet.Key.ToLower())
isFound = true;
baseAttribute.parentField.SetValue(classObject, value);
}
if (!isFound)
throw new InvalidOperationException($"Could not fill object. Data-Attribute '{data_keySet.Key}' was not found in class!");
dataMatchFound = true;
break;
}
// Check every class-field for match in data-attributes
foreach (KeyValuePair<string, FieldInfo> field_keySet in dbFields)
}
if (!dataMatchFound) throw new InvalidOperationException($"Attribute '{data_keySet.Key}' has no match in object '{classObject.GetType().Name}'");
}
}
/// <summary>
/// Gets an dbObject by primaryKey/s
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="classType">The classType (marked with Db-attributes)</param>
/// <param name="primaryKeyName">Name of the primaryKey</param>
/// <param name="primaryKeyValue">Value of the primaryKey</param>
/// <param name="primaryKeyData">KeyData of multiple primaryKeys</param>
/// <param name="queryExecutor">Function to handle query-calls</param>
public static T GetByPrimaryKey<T>(Type classType, object primaryKeyValue, Func<string, List<Dictionary<string, object>>> queryExecutor) where T : new()
{
bool isFound = false;
foreach (KeyValuePair<string, object> data_keySet in data)
// Read dbObject-attribute
DbObject dbObject = ClassAction.Init(classType);
if (dbObject.primaryKeyAttributes.Count < 1) throw new InvalidOperationException($"No primaryKey found in '{classType.Name}'");
if (dbObject.primaryKeyAttributes.Count > 1) throw new InvalidOperationException($"This 'GetByPrimaryKey' method only supports 1 primaryKey ('{dbObject.primaryKeyAttributes.Count}' found in '{classType.Name}')");
return GetByPrimaryKey<T>(classType, dbObject.primaryKeyAttributes[0]._attributeName, primaryKeyValue, queryExecutor);
}
/// <summary>
/// Gets an dbObject by primaryKey/s
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="classType">The classType (marked with Db-attributes)</param>
/// <param name="primaryKeyName">Name of the primaryKey</param>
/// <param name="primaryKeyValue">Value of the primaryKey</param>
/// <param name="primaryKeyData">KeyData of multiple primaryKeys</param>
/// <param name="queryExecutor">Function to handle query-calls</param>
public static T GetByPrimaryKey<T>(Type classType, string primaryKeyName, object primaryKeyValue, Func<string, List<Dictionary<string, object>>> queryExecutor) where T : new()
{
Dictionary<string, object> primaryKeyData = new Dictionary<string, object>() { };
primaryKeyData.Add(primaryKeyName, primaryKeyValue);
return GetByPrimaryKey<T>(classType, primaryKeyData, queryExecutor);
}
/// <summary>
/// Gets an dbObject by primaryKey/s
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="classType">The classType (marked with Db-attributes)</param>
/// <param name="primaryKeyName">Name of the primaryKey</param>
/// <param name="primaryKeyValue">Value of the primaryKey</param>
/// <param name="primaryKeyData">KeyData of multiple primaryKeys</param>
/// <param name="queryExecutor">Function to handle query-calls</param>
public static T GetByPrimaryKey<T>(Type classType, Dictionary<string, object> primaryKeyData, Func<string, List<Dictionary<string, object>>> queryExecutor) where T: new()
{
// Read dbObject-attribute
DbObject dbObject = ClassAction.Init(classType);
if (dbObject.primaryKeyAttributes.Count < 1) throw new InvalidOperationException($"No primaryKey found in '{classType.Name}'");
// Create new empty object
T obj = (T)dbObject.parentCInfo.Invoke(null);
// iterate thru them to check and fill object
foreach (DbPrimaryKey primaryKeyAtt in dbObject.primaryKeyAttributes)
{
bool dataMatchFound = false;
// Now search the corresponding primaryKeyData
foreach (KeyValuePair<string, object> primaryKey in primaryKeyData)
{
// primaryKey matches
if(primaryKeyAtt._attributeName.ToLower() == primaryKey.Key.ToLower())
{
if (field_keySet.Key.ToLower() == data_keySet.Key.ToLower())
isFound = true;
// Set data
primaryKeyAtt.parentField.SetValue(obj, primaryKey.Value);
dataMatchFound = true;
break;
}
}
if (!isFound)
throw new InvalidOperationException($"Could not fill object. Class-field '{field_keySet.Key}' was not found in data!");
// If no data was found matching this field
if (!dataMatchFound) throw new InvalidOperationException($"PrimaryKey='{primaryKeyAtt.parentField.Name}' is missing.");
}
try
{
ResolveByPrimaryKey<T>(obj, queryExecutor);
}catch(InvalidOperationException)
{
// If there is no result, return null
return default(T);
}
// Iterate through data
foreach (KeyValuePair<string, object> data_keySet in data)
return obj;
}
// ----
/// <summary>
/// Gets all dbObjects of class/table
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="classObject">Given object (marked with Db-attributes)</param>
/// <param name="queryExecutor">Function to handle query-calls</param>
public static List<T> GetList<T>(Type classType, Func<string, List<Dictionary<string, object>>> queryExecutor) where T : new()
{
// Interate through class-fields
foreach (KeyValuePair<string, FieldInfo> field_keySet in dbFields)
// Read dbObject - attribute
DbObject dbObject = ClassAction.Init(classType);
string query = QueryBuilder.SelectByAttribute(dbObject._tableName); // Generate query
List<Dictionary<string, object>> dataSet = queryExecutor(query); // Execute
List<T> objs = new List<T>() { };
foreach (Dictionary<string, object> data in dataSet)
{
// If its a match, set the value
if (field_keySet.Key.ToLower() == data_keySet.Key.ToLower())
T obj = new T(); // New object
FillObject(obj, data); // Fill it
objs.Add(obj); // Add to list
}
return objs; // Return list
}
/// <summary>
/// Gets a list of dbObjects by attribute/s
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="classType">Type of class</param>
/// <param name="fields">class-fields for select</param>
/// <param name="queryExecutor">Function to handle query-calls</param>
/// <returns>List of dbObjects</returns>
public static List<T> GetListByAttribute<T>(Type classType, Dictionary<string, object> fields, Func<string, List<Dictionary<string, object>>> queryExecutor) where T : new()
{
// Read dbObject-attribute
DbObject dbObject = ClassAction.Init(classType);
Function.ConvertAttributeToDbAttributes(classType, fields);
string query = QueryBuilder.SelectByAttribute(dbObject._tableName, fields); // Generate query
List<Dictionary<string, object>> dataSet = queryExecutor(query); // Execute
List<T> objs = new List<T>() { };
foreach (Dictionary<string, object> data in dataSet)
{
T obj = new T(); // New object
FillObject(obj, data); // Fill it
objs.Add(obj); // Add to list
}
return objs; // Return list
}
/// <summary>
/// Gets an dbObject by custom where-clause
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="classObject">Given object (marked with Db-attributes)</param>
/// <param name="whereClause">Custom where-clause params attached to query (SELECT * FROM tableName WHERE whereClause)</param>
/// <param name="queryExecutor">Function to handle query-calls</param>
public static List<T> GetListWithWhere<T>(Type classType, Func<string, List<Dictionary<string, object>>> queryExecutor, params object[] whereClause) where T : new()
{
// Read dbObject - attribute
DbObject dbObject = ClassAction.Init(classType);
string query = QueryBuilder.SelectWithWhere(dbObject._tableName, whereClause); // Generate query
List<Dictionary<string, object>> dataSet = queryExecutor(query); // Execute
List<T> objs = new List<T>() { };
foreach (Dictionary<string, object> data in dataSet)
{
T obj = new T(); // New object
FillObject(obj, data); // Fill it
objs.Add(obj); // Add to list
}
return objs; // Return list
}
/// <summary>
/// Gets an dbObject by full query
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="classObject">Given object (marked with Db-attributes)</param>
/// <param name="customQuery">Custom sql-query</param>
/// <param name="queryExecutor">Function to handle query-calls</param>
public static List<T> GetListWithQuery<T>(Type classType, Func<string, List<Dictionary<string, object>>> queryExecutor, params object[] customQuery) where T : new()
{
// Read dbObject - attribute
DbObject dbObject = ClassAction.Init(classType);
string query = QueryBuilder.BuildQuery(customQuery);
List<Dictionary<string, object>> dataSet = queryExecutor(query); // Execute
List<T> objs = new List<T>() { };
foreach (Dictionary<string, object> data in dataSet)
{
T obj = new T(); // New object
FillObject(obj, data); // Fill it
objs.Add(obj); // Add to list
}
return objs; // Return list
}
// -----
/// <summary>
/// Resolves dbObject by primaryKey/s<pragma/>
/// Object needs to have primaryKey/s set!
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="classObject">Given object (marked with Db-attributes)</param>
/// <param name="queryExecutor">Function to handle query-calls</param>
public static void ResolveByPrimaryKey<T>(T classObject, Func<string, List<Dictionary<string, object>>> queryExecutor, bool throwExceptions = true)
{
string query = QueryBuilder.SelectByPrimaryKey(classObject); // Generate query
List<Dictionary<string, object>> dataSet = queryExecutor(query); // Execute
if (dataSet.Count == 0)
{
if (throwExceptions) throw new InvalidOperationException($"Cannot fetch '{typeof(T).Name}' by primary key/s. No results!");
}
else FillObject(classObject, dataSet[0]); // Fill the object
}
/// <summary>
/// Resolves all foreignKeys with the database<pragma/>
/// Only works if the foreignKey is single (not assembled)!
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="classObject">Given object (marked with Db-attributes)</param>
/// <param name="queryExecutor">Function to handle query-calls</param>
/// <param name="max_depth">Determents how deep resolving will be executed</param>
public static void ResolveForeignKeys<T>(T classObject, Func<string, List<Dictionary<string, object>>> queryExecutor, int max_depth = 1) where T: new()
{
Type classType = classObject.GetType();
// Read dbObject-attribute
DbObject dbObject = ClassAction.Init(classType);
// Resolve foreignObjects
foreach (DbForeignObject foreignObjectAtt in dbObject.foreignObjectAttributes)
{
object foreignKey_value = foreignObjectAtt.foreignKeyAttribute.parentField.GetValue(classObject);
object foreignObject_value = foreignObjectAtt.parentField.GetValue(classObject);
// When key is set and object is empty, get it & set it
if(foreignKey_value != null && foreignObject_value == null)
{
// Resolve it
foreignObject_value = GetByPrimaryKey<T>(foreignObjectAtt.foreignObjectType, foreignKey_value, queryExecutor);
foreignObjectAtt.parentField.SetValue(classObject, foreignObject_value); // Set the value
// Now scan the just resolved class to be able to set myself
DbObject foreignDbObject = Init(foreignObject_value.GetType());
foreach(DbReverseForeignObject dbReverseForeignObject in foreignDbObject.reverseForeignObjectAttributes)
{
// If the field-names match
if(dbReverseForeignObject._foreignKeyName.ToLower() == dbObject.primaryKeyAttributes[0]._attributeName.ToLower())
{
object myReference;
if (dbReverseForeignObject.parentField.FieldType is IList && dbReverseForeignObject.parentField.FieldType.IsGenericType) // 1:m
{
// If its a list, i create a list with just myself
myReference = new List<T>() { classObject };
}
else // 1:1
{
// Otherwise ist just myself
myReference = classObject;
}
dbReverseForeignObject.parentField.SetValue(foreignObject_value, myReference);
break;
}
}
}
// Recursive resolving
if (max_depth > 1)
{
// Go recursively into the next class
ResolveForeignKeys(foreignObject_value, queryExecutor, max_depth - 1);
}
}
// Resolve intermediateForeignObjects
foreach (DbIntermediateForeignObject intermediateForeignObjectAtt in dbObject.intermediateObjectAttributes)
{
object intermediateForeignObject_value = intermediateForeignObjectAtt.parentField.GetValue(classObject);
// When its empty, get it & set it
if (intermediateForeignObject_value == null)
{
// Generate & set attribute-set
Dictionary<string, object> attributes = new Dictionary<string, object>();
attributes.Add(intermediateForeignObjectAtt._keyName, dbObject.primaryKeyAttributes[0].parentField.GetValue(classObject));
string query = QueryBuilder.SelectByAttribute(intermediateForeignObjectAtt._intermediateTableName, attributes); // Generate query
List<Dictionary<string, object>> dataSet = queryExecutor(query); // Execute
// Extract data
List<object> values = new List<object>();
for (int i=0; i<dataSet.Count; i++)
{
Dictionary<string, object> data = dataSet[i];
object primaryKeyValue = data[intermediateForeignObjectAtt.foreignPrimaryKeyAttribute._attributeName];
values.Add(GetByPrimaryKey<object>(intermediateForeignObjectAtt.foreignPrimaryKeyAttribute.classAttribute.parentClassType, primaryKeyValue, queryExecutor));
}
// Now scan the just resolved class to be able to set myself
DbObject foreignDbObject = Init(intermediateForeignObjectAtt.foreignPrimaryKeyAttribute.classAttribute.parentClassType);
foreach (DbForeignObject dbForeignObject in foreignDbObject.foreignObjectAttributes)
{
// If the field-names match
if (dbForeignObject._foreignKeyName.ToLower() == dbObject.primaryKeyAttributes[0]._attributeName.ToLower())
{
object myReference = classObject;
foreach (object value in values)
{
dbForeignObject.parentField.SetValue(value, myReference);
}
break;
}
}
// Set value
intermediateForeignObject_value = values;
intermediateForeignObjectAtt.parentField.SetValue(classObject, intermediateForeignObject_value);
}
// Recursive resolving
if (max_depth > 1)
{
// If we have a list of objects, we need to recursively go into each one
foreach (object value in (IList)intermediateForeignObject_value)
{
ResolveForeignKeys(value, queryExecutor, max_depth - 1);
}
}
}
// Resolve reverseForeignObjects
foreach (DbReverseForeignObject reverseForeignObjectAtt in dbObject.reverseForeignObjectAttributes)
{
object reverseForeignObject_value = reverseForeignObjectAtt.parentField.GetValue(classObject);
Type reverseForeignObject_type = reverseForeignObjectAtt.parentField.GetType();
// When its empty, get it & set it
if (reverseForeignObject_value == null)
{
field_keySet.Value.SetValue(classObject, data_keySet.Value);
// Generate & set attribute-set
Dictionary<string, object> attributes = new Dictionary<string, object>();
attributes.Add(reverseForeignObjectAtt._foreignKeyName, dbObject.primaryKeyAttributes[0].parentField.GetValue(classObject));
List<object> values = GetListByAttribute<object>(reverseForeignObjectAtt.foreignKeyAttribute.classAttribute.parentClassType, attributes, queryExecutor);
if(values.Count == 0) throw new InvalidOperationException($"'{reverseForeignObjectAtt.parentField.Name}' could not been resolved. ReverseForeignObject returned '{values.Count}' values.");
// Now scan the just resolved class to be able to set myself
DbObject foreignDbObject = Init(reverseForeignObjectAtt.foreignKeyAttribute.classAttribute.parentClassType);
foreach (DbForeignObject dbForeignObject in foreignDbObject.foreignObjectAttributes)
{
// If the field-names match
if (dbForeignObject._foreignKeyName.ToLower() == dbObject.primaryKeyAttributes[0]._attributeName.ToLower())
{
object myReference = classObject;
foreach(object value in values)
{
dbForeignObject.parentField.SetValue(value, myReference);
}
break;
}
}
// Check for type to determen 1:1 or 1:m
if (reverseForeignObject_type is IList && reverseForeignObject_type.IsGenericType) // List, so 1:m
{
reverseForeignObject_value = values;
}
else // Not list, so 1:1
{
if (values.Count > 1) throw new InvalidOperationException($"'{reverseForeignObjectAtt.parentField.Name}' could not been resolved as ReverseForeignObject returned '{values.Count}' values. (Is it 1:m instead of 1:1?)");
reverseForeignObject_value = values[0];
}
reverseForeignObjectAtt.parentField.SetValue(classObject, reverseForeignObject_value);
}
// Recursive resolving
if (max_depth > 1)
{
if (reverseForeignObject_value is IList && reverseForeignObject_type.IsGenericType) // 1:m
{
// If we have a list of objects, we need to recursively go into each one
foreach(object value in (IList)reverseForeignObject_value)
{
ResolveForeignKeys(value, queryExecutor, max_depth - 1);
}
}
else // 1:1
{
// Go recursively into the next class
ResolveForeignKeys(reverseForeignObject_value, queryExecutor, max_depth - 1);
}
}
}
}
/// <summary>
/// Resolves an object with the database<para/>
/// Needs to have primaryKey/s set!<para/>
/// - Generates an query<para/>
/// - Sends an query via Func<para/>
/// - Fills the object with data
/// Updates class to database-object</pragma>
/// Only works with primary-key/s!
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="classObject">Given object (marked with Db-attributes)</param>
/// <param name="queryExecutor">Function to handle query-calls - Has to return Dictionary[attributeName, attributeValue]</param>
/// <param name="runDataLossChecks">This checks if any class-field and data-attribute does not exists in either (Slower)</param>
public static void ResolveByPrimaryKey<T>(T classObject, Func<string, List<Dictionary<string, object>>> queryExecutor, bool runDataLossChecks = true)
/// <param name="queryExecutor">Function to handle query-calls</param>
/// <param name="max_depth">Determents how deep resolving will be executed (if the corresponding foreignKey-object is resolved)</param>
public static void Update<T>(T classObject, Func<string, List<Dictionary<string, object>>> queryExecutor, int max_depth = 1)
{
// Read dbObject-attribute
DbObject dbObject = ClassAction.Init(classObject.GetType());
if(max_depth-1 > 0)
{
// Update all foreignObjects before handling myself
foreach (DbForeignObject foreignObject in dbObject.foreignObjectAttributes)
{
string query = QueryBuilder.SelectByPrimaryKey(classObject);
List<Dictionary<string, object>> dataSet = queryExecutor(query);
FillObject(classObject, dataSet[0], runDataLossChecks);
object foreignObjectRef = foreignObject.parentField.GetValue(classObject);
if (foreignObjectRef != null)
Update(foreignObjectRef, queryExecutor, max_depth - 1);
}
}
string updateQuery = QueryBuilder.UpdateByPrimaryKey(classObject);
queryExecutor.Invoke(updateQuery);
}
/// <summary>
/// Inserts class to database-object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="classObject">Given object (marked with Db-attributes)</param>
/// <param name="queryExecutor">Function to handle query-calls</param>
/// <param name="max_depth">Determents how deep insertion will be executed (if the corresponding foreignKey-object is resolved)</param>
public static void Insert<T>(T classObject, Func<string, List<Dictionary<string, object>>> queryExecutor, int max_depth = 1)
{
// Read dbObject-attribute
DbObject dbObject = ClassAction.Init(classObject.GetType());
if (max_depth - 1 > 0)
{
// Update all foreignObjects before handling myself
foreach (DbForeignObject foreignObject in dbObject.foreignObjectAttributes)
{
object foreignObjectRef = foreignObject.parentField.GetValue(classObject);
if (foreignObjectRef != null)
Insert(foreignObjectRef, queryExecutor, max_depth - 1);
}
}
string insertQuery = QueryBuilder.InsertAttributesByObject(classObject);
queryExecutor.Invoke(insertQuery);
}
/// <summary>
/// Deletes class from database-object</pragma>
/// Only works with primary-key/s!
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="classObject">Given object (marked with Db-attributes)</param>
/// <param name="queryExecutor">Function to handle query-calls</param>
/// <param name="max_depth">Determents how deep deletion will be executed (if the corresponding foreignKey-object is resolved)</param>
public static void Delete<T>(T classObject, Func<string, List<Dictionary<string, object>>> queryExecutor, int max_depth = 1)
{
// Read dbObject-attribute
DbObject dbObject = ClassAction.Init(classObject.GetType());
if (max_depth - 1 > 0)
{
// Update all foreignObjects before handling myself
foreach (DbForeignObject foreignObject in dbObject.foreignObjectAttributes)
{
object foreignObjectRef = foreignObject.parentField.GetValue(classObject);
if (foreignObjectRef != null)
Delete(foreignObjectRef, queryExecutor, max_depth - 1);
}
}
string deleteQuery = QueryBuilder.DeleteByPrimaryKey(classObject);
queryExecutor.Invoke(deleteQuery);
}
}
}

@ -4,7 +4,7 @@
<TargetFramework>netcoreapp2.1</TargetFramework>
<RootNamespace>eu.railduction.netcore.dll.Database_Attribute_System</RootNamespace>
<SignAssembly>false</SignAssembly>
<Version>1.2.3</Version>
<Version>1.5.3</Version>
</PropertyGroup>
</Project>

@ -8,33 +8,24 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
public class QueryBuilder
{
/// <summary>
/// Builds an SELECT-Sql-query based on an object<para/>
/// Object needs to have at least 1 primary-key!
/// Builds an SELECT-Sql-query based on an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="classObject">Given object (marked with Db-attributes)</param>
/// <param name="tableName">The db-table-name</param>
/// <returns>SELECT-Sql-query</returns>
public static string SelectByPrimaryKey<T>(T classObject)
{
Type classType = classObject.GetType();
// Get db-table-name from class
string tableName = Function.GetDbTableName(classType);
// Get class db-fields
Dictionary<string, object> dbPrimaryKeys = new Dictionary<string, object>() { };
Dictionary<string, object> dbAttributes = new Dictionary<string, object>() { };
Dictionary<string, object> dbForeignKeys = new Dictionary<string, object>() { };
Function.ReadDbClassFields(classObject, ref dbPrimaryKeys, ref dbAttributes, ref dbForeignKeys);
if (dbPrimaryKeys.Count == 0) throw new InvalidOperationException($"Cannot generate SQL-Query of '{classType.Name}'. No primary-key/s found!");
// Read dbObject-attribute
DbObject dbObject = ClassAction.Init(classType);
// Build where statements with primaryKey/s
object[] param = DbFunction.BuildKeyEqualQuery(dbPrimaryKeys, " AND ");
// Add SQL-command part
param[0] = $"SELECT * FROM {tableName} WHERE "+ param[0];
// Check if 'byPrimaryKey' is possible
if (dbObject.primaryKeyAttributes.Count == 0) throw new InvalidOperationException($"Cannot generate SQL-Query of '{classType.Name}'. No primary-key/s!");
Dictionary<string, object> dbPrimaryKeys = Function.ReadFieldData(Function.ConvertToDerivedList(dbObject.primaryKeyAttributes), classObject);
// Build and return the query
return BuildQuery(param);
return SelectByAttribute(dbObject._tableName, dbPrimaryKeys);
}
/// <summary>
@ -42,53 +33,47 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
/// Object needs to have at least 1 attribute!
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="classObject">Given object (marked with Db-attributes)</param>
/// <param name="attributeNames">Attributes and/or foreignKeys to use in lookup</param>
/// <param name="tableName">The db-table-name</param>
/// <param name="dbAttributes">The db-attributes with dbAttribute-name and value<para/>If null is given, it will generate a default 'SELECT * FROM tableName'</param>
/// <returns>SELECT-Sql-query</returns>
public static string SelectByAttribute<T>(T classObject, params string[] attributeNames)
public static string SelectByAttribute(string tableName, Dictionary<string, object> dbAttributes = null)
{
Type classType = classObject.GetType();
// Get db-table-name from class
string tableName = Function.GetDbTableName(classType);
// Get class db-fields
Dictionary<string, object> dbPrimaryKeys = new Dictionary<string, object>() { };
Dictionary<string, object> dbAttributes = new Dictionary<string, object>() { };
Dictionary<string, object> dbForeignKeys = new Dictionary<string, object>() { };
Function.ReadDbClassFields(classObject, ref dbPrimaryKeys, ref dbAttributes, ref dbForeignKeys);
if (dbAttributes.Count == 0) throw new InvalidOperationException($"Cannot generate SQL-Query of '{classType.Name}'. No attribute found!");
Dictionary<string, object> attributes = new Dictionary<string, object>() { };
// Iterate through given names
foreach (string attributeName in attributeNames)
{
// Iterate through attributes of class
foreach (KeyValuePair<string, object> dbAttribute in dbAttributes)
{
// If its a match, copy it to list
if (dbAttribute.Key.ToLower() == attributeName.ToLower())
{
attributes.Add(dbAttribute.Key, dbAttribute.Value);
}
}
}
object[] param = new object[1];
if (attributeNames != null)
if (dbAttributes != null)
{
// Build where statements with primaryKey/s
param = DbFunction.BuildKeyEqualQuery(attributes, " AND ");
param = DbFunction.BuildKeyEqualQuery(dbAttributes, " AND ");
}
string sqlCmd = $"SELECT * FROM {tableName}";
// Add SQL-command part
param[0] = $"SELECT * FROM {tableName} WHERE " + param[0];
if (dbAttributes != null)
param[0] = $"{sqlCmd} WHERE {param[0]}";
else
param[0] = sqlCmd;
// Build and return the query
return BuildQuery(param);
}
/// <summary>
/// Builds an SELECT-Sql-query based on an object with custom where clause<para/>
/// Object needs to have at least 1 attribute!
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tableName">The db-table-name</param>
/// <param name="whereClause">Custom where-clause params attached to query (SELECT * FROM tableName WHERE whereClause)</param>
/// <returns>SELECT-Sql-query</returns>
public static string SelectWithWhere(string tableName, params object[] whereClause)
{
string sqlCmd = $"SELECT * FROM {tableName}";
// Add SQL-command part
if (!(whereClause[0] is string)) throw new InvalidOperationException("Cannot generate SQL-query. WhereClause-params not starting with string!");
whereClause[0] = $"{sqlCmd} WHERE {whereClause[0]}";
// Build and return the query
return BuildQuery(whereClause);
}
/// <summary>
/// Builds an UPDATE-Sql-query based on an object<para/>
@ -101,15 +86,14 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
{
Type classType = classObject.GetType();
// Get db-table-name from class
string tableName = Function.GetDbTableName(classType);
// Read dbObject-attribute
DbObject dbObject = ClassAction.Init(classType);
// Get class db-fields
Dictionary<string, object> dbPrimaryKeys = new Dictionary<string, object>() { };
Dictionary<string, object> dbAttributes = new Dictionary<string, object>() { };
Dictionary<string, object> dbForeignKeys = new Dictionary<string, object>() { };
Function.ReadDbClassFields(classObject, ref dbPrimaryKeys, ref dbAttributes, ref dbForeignKeys);
if (dbPrimaryKeys.Count == 0) throw new InvalidOperationException($"Cannot generate SQL-Query of '{classType.Name}'. No primary-key/s found!");
// Check if 'byPrimaryKey' is possible
if (dbObject.primaryKeyAttributes.Count == 0) throw new InvalidOperationException($"Cannot generate SQL-Query of '{classType.Name}'. No primary-key/s!");
Dictionary<string, object> dbPrimaryKeys = Function.ReadFieldData(Function.ConvertToDerivedList(dbObject.primaryKeyAttributes), classObject);
Dictionary<string, object> dbForeignKeys = Function.ReadFieldData(Function.ConvertToDerivedList(dbObject.foreignKeyAttributes), classObject);
Dictionary<string, object> dbAttributes = Function.ReadFieldData(Function.ConvertToDerivedList(dbObject.attributeAttributes), classObject);
// Add foreign-keys to attributes
foreach (KeyValuePair<string, object> dbForeignKey in dbForeignKeys)
@ -120,7 +104,7 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
// Build set-parameters
object[] paramSet = DbFunction.BuildKeyEqualQuery(dbAttributes, ", ");
// Add SQL-command part
paramSet[0] = $"UPDATE {tableName} SET "+ paramSet[0];
paramSet[0] = $"UPDATE {dbObject._tableName} SET "+ paramSet[0];
// Build where-parameters
object[] paramWhere = DbFunction.BuildKeyEqualQuery(dbPrimaryKeys, " AND ");
@ -142,80 +126,101 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
{
Type classType = classObject.GetType();
// Get db-table-name from class
string tableName = Function.GetDbTableName(classType);
// Read dbObject-attribute
DbObject dbObject = ClassAction.Init(classType);
// Get class db-fields
Dictionary<string, object> dbPrimaryKeys = new Dictionary<string, object>() { };
Dictionary<string, object> dbAttributes = new Dictionary<string, object>() { };
Dictionary<string, object> dbForeignKeys = new Dictionary<string, object>() { };
Function.ReadDbClassFields(classObject, ref dbPrimaryKeys, ref dbAttributes, ref dbForeignKeys);
if (dbPrimaryKeys.Count == 0) throw new InvalidOperationException($"Cannot generate SQL-Query of '{classType.Name}'. No primary-key/s found!");
// Check if 'byPrimaryKey' is possible
if (dbObject.primaryKeyAttributes.Count == 0) throw new InvalidOperationException($"Cannot generate SQL-Query of '{classType.Name}'. No primary-key/s!");
Dictionary<string, object> dbPrimaryKeys = Function.ReadFieldData(Function.ConvertToDerivedList(dbObject.primaryKeyAttributes), classObject);
// Build where-parameters
object[] paramWhere = DbFunction.BuildKeyEqualQuery(dbPrimaryKeys, " AND ");
// Build and return the query
return DeleteByAttribute(dbObject._tableName, dbPrimaryKeys);
}
public static string DeleteByAttribute(string tableName, Dictionary<string, object> dbAttributes = null)
{
object[] param = new object[1];
if (dbAttributes != null)
{
// Build where statements with primaryKey/s
param = DbFunction.BuildKeyEqualQuery(dbAttributes, " AND ");
}
string sqlCmd = $"DELETE FROM {tableName}";
// Add SQL-command part
paramWhere[0] = $"DELETE FROM {tableName} WHERE "+ paramWhere[0];
if (dbAttributes != null)
param[0] = $"{sqlCmd} WHERE {param[0]}";
else
param[0] = sqlCmd;
// Build and return the query
return BuildQuery(paramWhere);
return BuildQuery(param);
}
/// <summary>
/// Builds an DELETE-Sql-query based on an object<para/>
/// Object needs to have at least 1 primary-key!
/// Builds an INSERT-Sql-query based on an object<para/>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="classObject">Given object (marked with Db-attributes)</param>
/// <param name="attributeNames">Attributes and/or foreignKeys to use in lookup</param>
/// <returns>DELETE-Sql-query</returns>
public static string DeleteByAttribute<T>(T classObject, params string[] attributeNames)
/// <param name="tableName"></param>
/// <param name="dbAttributes"></param>
/// <returns></returns>
public static string InsertAttributesByObject<T>(T classObject)
{
Type classType = classObject.GetType();
// Get db-table-name from class
string tableName = Function.GetDbTableName(classType);
// Get class db-fields
Dictionary<string, object> dbPrimaryKeys = new Dictionary<string, object>() { };
Dictionary<string, object> dbAttributes = new Dictionary<string, object>() { };
Dictionary<string, object> dbForeignKeys = new Dictionary<string, object>() { };
Function.ReadDbClassFields(classObject, ref dbPrimaryKeys, ref dbAttributes, ref dbForeignKeys);
if (dbAttributes.Count == 0) throw new InvalidOperationException($"Cannot generate SQL-Query of '{classType.Name}'. No attribute found!");
// Read dbObject-attribute
DbObject dbObject = ClassAction.Init(classType);
Dictionary<string, object> attributes = new Dictionary<string, object>() { };
// Iterate through given names
foreach (string attributeName in attributeNames)
List<string> attributes = new List<string>() { };
List<object> data = new List<object>() { };
foreach(BaseAttribute baseAttribute in dbObject.baseAttributes)
{
// Iterate through attributes of class
foreach (KeyValuePair<string, object> dbAttribute in dbAttributes)
attributes.Add(baseAttribute._attributeName);
data.Add(baseAttribute.parentField.GetValue(classObject));
}
return InsertAttributes(dbObject._tableName, attributes, data);
}
public static string InsertAttributes(string tableName, Dictionary<string, object> dbAttributes)
{
// If its a match, copy it to list
if (dbAttribute.Key.ToLower() == attributeName.ToLower())
if (dbAttributes.Count == 0) throw new InvalidOperationException("Cannot generate SQL-Query. No attributes to insert.");
List<string> attributes = new List<string>() { };
List<object> data = new List<object>() { };
foreach (KeyValuePair<string, object> attribute in dbAttributes)
{
attributes.Add(dbAttribute.Key, dbAttribute.Value);
}
attributes.Add(attribute.Key);
data.Add(attribute.Value);
}
return InsertAttributes(tableName, attributes, data);
}
public static string InsertAttributes(string tableName, List<string> attributes, List<object> data)
{
if (attributes.Count != data.Count) throw new InvalidOperationException("Cannot generate SQL-Query. Attribute-count and data-count not equal.");
object[] param = new object[1];
if (attributeNames != null)
string attributesSeperatedByComma = "";
object[] attributeData = new object[attributes.Count*2 -1];
int c = 0;
for(int i=0; i< attributes.Count; i++)
{
// Build where statements with primaryKey/s
param = DbFunction.BuildKeyEqualQuery(attributes, " AND ");
}
attributesSeperatedByComma += attributes[i];
attributeData[c] = data[i];
// Add SQL-command part
param[0] = $"DELETE FROM {tableName} WHERE " + param[0];
if(c+1 != attributeData.Length)
{
attributesSeperatedByComma += ", ";
attributeData[c+1] = ",";
}
c +=2;
}
// Build and return the query
return BuildQuery(param);
return BuildQuery($"INSERT INTO {tableName} ({attributesSeperatedByComma}) VALUES (", attributeData, ")");
}
/// <summary>
/// Build an SQL-query<para/>
/// Will build the query-string based on the <paramref name="param"/>s including serialising and escaping for SQL.<para/>

@ -14,11 +14,6 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
return str_cpy;
}
public static string SqlSerialise(DateTime dt, string format = "yyyy-MM-dd HH:mm:ss")
{
return dt.ToString(format);
}
// Recursive object[] copying
internal static void RecursiveParameterCopying(ref List<object> paramz, object[] objects)
{
@ -31,100 +26,117 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
}
}
internal static void ReadDbClassFields<T>(T classObject, ref Dictionary<string, object> dbPrimaryKeys, ref Dictionary<string, object> dbAttributes, ref Dictionary<string, object> dbForeignKeys)
internal static List<BaseAttribute> ConvertToDerivedList(List<DbPrimaryKey> list)
{
Type classType = typeof(T);
// Reset lists (just in case)
dbPrimaryKeys = new Dictionary<string, object>() { };
dbAttributes = new Dictionary<string, object>() { };
dbForeignKeys = new Dictionary<string, object>() { };
// Iterate thru all properties
foreach (System.Reflection.FieldInfo fi in classType.GetRuntimeFields())
{
// Check if current field is a db-field
if (fi.GetCustomAttribute(typeof(DbPrimaryKey), true) is DbPrimaryKey pkey) // PrimaryKey
List<BaseAttribute> derivedList = new List<BaseAttribute>() { };
foreach (BaseAttribute key in list)
{
string dbAttributeName = pkey._attributeName ?? fi.Name; // If no alternative attribute-name is specified, use the property-name
object value = fi.GetValue(classObject);
dbPrimaryKeys.Add(dbAttributeName, value);
derivedList.Add(key);
}
else if (fi.GetCustomAttribute(typeof(DbAttribute), true) is DbAttribute att) // Attributes
{
string dbAttributeName = att._attributeName ?? fi.Name; // If no alternative attribute-name is specified, use the property-name
object value = fi.GetValue(classObject);
dbAttributes.Add(dbAttributeName, value);
return derivedList;
}
else if (fi.GetCustomAttribute(typeof(DbForeignKey), true) is DbForeignKey fkey) // ForeignKeys
internal static List<BaseAttribute> ConvertToDerivedList(List<DbAttribute> list)
{
string dbAttributeName = fkey._attributeName ?? fi.Name; // If no alternative attribute-name is specified, use the property-name
object value = fi.GetValue(classObject);
dbForeignKeys.Add(dbAttributeName, value);
List<BaseAttribute> derivedList = new List<BaseAttribute>() { };
foreach (BaseAttribute key in list)
{
derivedList.Add(key);
}
return derivedList;
}
internal static List<BaseAttribute> ConvertToDerivedList(List<DbForeignKey> list)
{
List<BaseAttribute> derivedList = new List<BaseAttribute>() { };
foreach (BaseAttribute key in list)
{
derivedList.Add(key);
}
return derivedList;
}
internal static Dictionary<string, FieldInfo> ReadDbClassFields<T>(T classObject)
internal static Dictionary<string, object> ReadFieldData<T>(List<BaseAttribute> fieldAttributes, T classObject)
{
Type classType = typeof(T);
Dictionary<string, object> fieldData = new Dictionary<string, object>() { };
Dictionary<string, FieldInfo> dbFields = new Dictionary<string, FieldInfo>();
foreach (BaseAttribute attribute in fieldAttributes)
{
// Read the data and add it
fieldData.Add(
attribute._attributeName,
attribute.parentField.GetValue(classObject)
);
}
// Iterate thru all properties
foreach (System.Reflection.FieldInfo fi in classType.GetRuntimeFields())
return fieldData; // Return the data
}
internal static void ConvertAttributeToDbAttributes(Type classType, Dictionary<string, object> attributeNameAndValues)
{
// Check if current field is a db-field
if (fi.GetCustomAttribute(typeof(DbPrimaryKey), true) is DbPrimaryKey pkey) // PrimaryKey
// Read dbObject-attribute
DbObject dbObject = ClassAction.Init(classType);
Dictionary<string, object> convertedAttributeNameAndValues = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> attributeNameAndValue in attributeNameAndValues)
{
string dbAttributeName = pkey._attributeName ?? fi.Name; // If no alternative attribute-name is specified, use the property-name
dbFields.Add(dbAttributeName, fi);
}
else if (fi.GetCustomAttribute(typeof(DbAttribute), true) is DbAttribute att) // Attributes
bool nameFound = false;
foreach (BaseAttribute baseAttribute in dbObject.baseAttributes)
{
string dbAttributeName = att._attributeName ?? fi.Name; // If no alternative attribute-name is specified, use the property-name
dbFields.Add(dbAttributeName, fi);
}
else if (fi.GetCustomAttribute(typeof(DbForeignKey), true) is DbForeignKey fkey) // ForeignKeys
if (attributeNameAndValue.Key.ToLower() == baseAttribute.parentField.Name.ToLower())
{
string dbAttributeName = fkey._attributeName ?? fi.Name; // If no alternative attribute-name is specified, use the property-name
dbFields.Add(dbAttributeName, fi);
convertedAttributeNameAndValues.Add(baseAttribute._attributeName, attributeNameAndValue.Value);
nameFound = true;
break;
}
}
return dbFields;
if (!nameFound) throw new InvalidOperationException($"'{attributeNameAndValue.Key}' has no classField!");
}
}
internal static void ConvertAttributeToDbAttributes(Type classType, List<string> attributeNames)
{
// Read dbObject-attribute
DbObject dbObject = ClassAction.Init(classType);
public static string GetDbTableName(Type classType)
for(int i=0; i< dbObject.baseAttributes.Count; i++)
{
// Check if class has attribute 'DbObject' and get the database table-name
if (!(classType.GetCustomAttribute(typeof(DbObject), true) is DbObject dbObjectAttribute)) throw new InvalidOperationException($"Cannot generate SQL-Query of '{classType.Name}'. Missing Attribute 'DbObject'");
string tableName = dbObjectAttribute._tableName ?? classType.Name; // If no alternative table-name is specified, use the class-name
bool nameFound = false;
foreach (BaseAttribute baseAttribute in dbObject.baseAttributes)
{
if(attributeNames[i].ToLower() == baseAttribute.parentField.Name.ToLower())
{
attributeNames[i] = baseAttribute._attributeName;
nameFound = true;
break;
}
}
return tableName;
if (!nameFound) throw new InvalidOperationException($"'{attributeNames[i]}' has no classField!");
}
}
public static string SqlSerialise(object obj)
{
if (obj == null) // Handle null
if (obj == null || obj is DBNull) // Handle null
{
return "null";
}
else if (obj.GetType() == typeof(string)) // Handle strings
else if (obj is string) // Handle strings
{
return "'" + SqlEscape((string)obj) + "'"; // wrap in sql-brackets and escape sql, if any
}
else if (obj.GetType() == typeof(byte) || obj.GetType() == typeof(int) || obj.GetType() == typeof(float) || obj.GetType() == typeof(double)) // Handle int, float & double
else if (obj is byte || obj is int || obj is float || obj is double) // Handle int, float & double
{
return obj.ToString().Replace(",", "."); // just format to string and form comma to sql-comma
}
else if (obj.GetType() == typeof(DateTime)) // Handle DateTime
else if (obj is DateTime) // Handle DateTime
{
DateTime dateTime = (DateTime)obj;
return "'" + SqlSerialise(dateTime) + "'"; // wrap in sql-brackets and convert to sql-datetime
return "'" + dateTime.ToString("yyyy-MM-dd HH:mm:ss") + "'"; // wrap in sql-brackets and convert to sql-datetime
}
else if (obj.GetType() == typeof(Guid)) // Handle DateTime
else if (obj is Guid) // Handle Guid
{
string guid = ((Guid)obj).ToString(); // Get Guid as string
return "'" + guid + "'"; // wrap in sql-brackets

Loading…
Cancel
Save