private void build(System.Reflection.PropertyInfo property, System.Data.Linq.Mapping.ColumnAttribute attribute, Table table, SpecificationEnum specification) { this._key = (attribute.Name != null ? attribute.Name : attribute.Storage.Substring(1)).Trim(); if (this._key == property.Name) { throw new Gale.Exception.GaleException("API008", property.Name); } this._name = char.ToLower(property.Name[0]) + property.Name.Substring(1); this._type = property.PropertyType; this._table = table; this._specification = specification; this._selected = false; if (attribute.IsPrimaryKey) { _specification = SpecificationEnum.Pk; table.SetPrimaryKey(this); if (attribute.IsPrimaryKey && table.IsForeign == false) { this._selected = true; } } }
protected override string BuildDbTypeWithoutNullability(ColumnAttribute columnAttribute) { if (columnAttribute == null) { throw new ArgumentNullException("columnAttribute"); } return((isRowVersion ?? false) ? "rowversion" : base.BuildDbTypeWithoutNullability(columnAttribute)); }
/// <summary> /// Add each parameter binded to a source in the Model /// </summary> /// <param name="Model"></param> public void FromModel <T>(T Model) { Type EntityType = typeof(T); var properties = ( from t in EntityType.GetProperties() where t.CanRead && t.GetIndexParameters().Count() == 0 && (t.PropertyType.IsGenericType == false || (t.PropertyType.IsGenericType == true && t.PropertyType.GetGenericTypeDefinition() != typeof(System.Data.Linq.EntitySet <>))) select t); //Add Each Parameter in the collection =)! foreach (var property in properties) { Object value = property.GetValue(Model); if (value != null) { Type propertyType = value.GetType(); //if (typeof(System.Collections.IEnumerable).IsAssignableFrom(propertyType)) if (propertyType.IsArray) { continue; } if (!propertyType.IsSimpleType()) { //Loop Over the Model Class MethodInfo method = this.GetType().GetMethod("FromModel"); MethodInfo generic = method.MakeGenericMethod(value.GetType()); generic.Invoke(this, new object[] { value }); } else { String db_name = property.Name; var attr = property.TryGetAttribute <System.Data.Linq.Mapping.ColumnAttribute>(); if (attr != null) { System.Data.Linq.Mapping.ColumnAttribute column_attr = (attr as System.Data.Linq.Mapping.ColumnAttribute); if (column_attr != null && column_attr.Name != null && column_attr.Name.Length > 0) { db_name = column_attr.Name; } } else { continue; } //Add Parameter this.Parameters.Add(db_name, value); } } } }
protected void CopyEntity(Object DestObj, Object SrcObj) { Type type = SrcObj.GetType(); PropertyInfo[] p = type.GetProperties(); for (int i = 0; i < p.Length; i++) { if (p[i].GetCustomAttributes(false)[0] is System.Data.Linq.Mapping.ColumnAttribute) { System.Data.Linq.Mapping.ColumnAttribute att = (System.Data.Linq.Mapping.ColumnAttribute)(p[i].GetCustomAttributes(false)[0]); //如果是主键,就不去更新copy if (att.IsPrimaryKey == false && att.IsDbGenerated == false) { p[i].SetValue(DestObj, p[i].GetValue(SrcObj, null), null); } } } }
public override Task <HttpResponseMessage> ExecuteAsync(System.Threading.CancellationToken cancellationToken) { Gale.Exception.GaleException.Guard(() => this.modelType == null, System.Net.HttpStatusCode.BadRequest, "API_EMPTY_BODY"); SortedDictionary <string, object> values = new SortedDictionary <string, object>(); var table_name = this.modelType.Name; #region BIND DATA var fieldProperties = typeof(TModel).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(System.Data.Linq.Mapping.ColumnAttribute))).ToList(); foreach (System.Reflection.PropertyInfo property in fieldProperties) { string db_name = property.Name; object value = null; if (property.GetValue(_payload) == null) { continue; } var attr = property.TryGetAttribute <System.Data.Linq.Mapping.ColumnAttribute>(); if (attr != null) { System.Data.Linq.Mapping.ColumnAttribute column_attr = (attr as System.Data.Linq.Mapping.ColumnAttribute); if (column_attr != null && column_attr.Name != null && column_attr.Name.Length > 0) { db_name = column_attr.Name; } } try { value = property.GetValue(_payload); } catch /*(System.Reflection.TargetInvocationException ex)*/ { throw new Gale.Exception.GaleException("API_CANT_SETVALUE", property.Name, table_name); } //Add as Data Value values.Add(db_name, value); } #endregion var table_attr = this.modelType.TryGetAttribute <System.Data.Linq.Mapping.TableAttribute>(); if (table_attr != null && table_attr.Name != null && table_attr.Name.Length > 0) { table_name = table_attr.Name; } #region SQL Builder /* * * BEGIN * DECLARE @TABLE_NAME VARCHAR(200) = '{TABLE}'; * DECLARE @OBJECT_ID INT = (SELECT object_id FROM sys.all_objects WHERE type_desc = 'USER_TABLE' AND name = @TABLE_NAME); * DECLARE @COUNT INT= (SELECT COUNT(*) FROM sys.identity_columns WHERE object_id = @OBJECT_ID); * * INSERT INTO TABLE ( * {FIELD} * ) VALUES ( * {VALUE} * ); * * IF(@COUNT = 1) * BEGIN * DECLARE @IDENTITY_COLUMN SYSNAME; * SELECT TOP 1 * @IDENTITY_COLUMN = name * FROM * sys.identity_columns WHERE object_id = @OBJECT_ID; * * DECLARE @GETLASTROWINSERTED NVARCHAR(4000) = 'SELECT ' + @TABLE_NAME + '.* FROM ' + @TABLE_NAME + ' WHERE ' + @IDENTITY_COLUMN + ' = ' + CONVERT(VARCHAR(200), SCOPE_IDENTITY()); * EXECUTE sp_executesql @GETLASTROWINSERTED; * END * ELSE * RAISERROR ('MORE_THAN_ONE_PK',12,1); * * END * * */ System.Text.StringBuilder builder = new StringBuilder(); builder.AppendFormat("INSERT INTO {0} ", table_name); builder.AppendFormat("( \n"); bool isFirst = true; foreach (var value in values) { if (!isFirst) { builder.Append(","); } builder.AppendFormat("{0} \n", value.Key); isFirst = false; } builder.Append(") VALUES ( \n"); isFirst = true; foreach (var value in values) { if (!isFirst) { builder.Append(","); } builder.AppendFormat("'{0}' \n", value.Value); isFirst = false; } builder.Append("); \n\n"); string single_tableName = table_name.Substring(table_name.IndexOf(".") + 1); //GET COUNT FROM IDENTITY COLUMNS FOR A SPECIFIC TABLE builder.AppendFormat("SELECT \n"); builder.AppendFormat(" COUNT(*) \n"); builder.AppendFormat("FROM \n"); builder.AppendFormat(" sys.identity_columns IDENT INNER JOIN \n"); builder.AppendFormat(" sys.all_objects TBLES ON IDENT.object_id = TBLES.object_id \n"); builder.AppendFormat(" AND type_desc = 'USER_TABLE' \n"); builder.AppendFormat(" AND TBLES.name = '{0}'; \n\n", single_tableName); //GET THE LAST INSERTED ROW (ONLY WORKS FOR A SINGLE PRIMARY KEY COLUMN) builder.AppendFormat("SELECT TOP 1 \n"); builder.AppendFormat(" IDENT.name \n"); builder.AppendFormat("FROM \n"); builder.AppendFormat(" sys.identity_columns IDENT INNER JOIN \n"); builder.AppendFormat(" sys.all_objects TBLES ON IDENT.object_id = TBLES.object_id \n"); builder.AppendFormat(" AND type_desc = 'USER_TABLE' \n"); builder.AppendFormat(" AND TBLES.name = '{0}' ", single_tableName); string query = builder.ToString(); #endregion //------------------------------------------------------------------------------------- //---[ DATABASE CALL using (Gale.Db.DataService svc = new Gale.Db.DataService(query)) { try { //Create the repository this.ExecuteSql(svc); HttpResponseMessage response = new HttpResponseMessage(System.Net.HttpStatusCode.Created) { Content = new StringContent("Created") }; return(Task.FromResult(response)); } catch (System.Exception ex) { string message = ex.InnerException != null ? ex.InnerException.Message : ex.Message; throw new Gale.Exception.GaleException("API_DB_ERROR", message); } } //------------------------------------------------------------------------------------- }
public Field(System.Reflection.PropertyInfo property, System.Data.Linq.Mapping.ColumnAttribute attribute, Table table, SpecificationEnum specification) { build(property, attribute, table, specification); }
public override Task <HttpResponseMessage> ExecuteAsync(System.Threading.CancellationToken cancellationToken) { Gale.Exception.GaleException.Guard(() => _payload == null, System.Net.HttpStatusCode.BadRequest, "API_EMPTY_BODY"); var table_type = typeof(TModel); SortedDictionary <string, object> values = new SortedDictionary <string, object>(); string table_name = table_type.Name; string primaryKey_name = null; #region BIND DATA var fieldProperties = typeof(TModel).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(System.Data.Linq.Mapping.ColumnAttribute))).ToList(); foreach (System.Reflection.PropertyInfo property in fieldProperties) { string db_name = property.Name; object value = null; var attr = property.TryGetAttribute <System.Data.Linq.Mapping.ColumnAttribute>(); if (attr != null) { System.Data.Linq.Mapping.ColumnAttribute column_attr = (attr as System.Data.Linq.Mapping.ColumnAttribute); if (column_attr != null && column_attr.Name != null && column_attr.Name.Length > 0) { db_name = column_attr.Name; if (column_attr.IsPrimaryKey) { primaryKey_name = db_name; continue; } } } if (property.GetValue(_payload) == null) { continue; } try { value = property.GetValue(_payload); } catch /*(System.Reflection.TargetInvocationException ex)*/ { throw new Gale.Exception.GaleException("API_CANT_SETVALUE", property.Name, table_name); } //Add as Data Value values.Add(db_name, value); } #endregion var table_attr = table_type.TryGetAttribute <System.Data.Linq.Mapping.TableAttribute>(); if (table_attr != null && table_attr.Name != null && table_attr.Name.Length > 0) { table_name = table_attr.Name; } #region SQL Builder System.Text.StringBuilder builder = new StringBuilder(); builder.AppendFormat("UPDATE {0} ", table_name); builder.AppendFormat(" SET"); bool isFirst = true; foreach (var value in values) { if (!isFirst) { builder.Append(","); } builder.AppendFormat(" {0} = '{1}'", value.Key, value.Value.ToString()); isFirst = false; } builder.AppendFormat(" WHERE"); builder.AppendFormat(" {0} = '{1}'", primaryKey_name, this.id); string query = builder.ToString(); #endregion //------------------------------------------------------------------------------------- //---[ DATABASE CALL using (Gale.Db.DataService svc = new Gale.Db.DataService(query)) { try { //Create the repository this.ExecuteSql(svc); HttpResponseMessage response = new HttpResponseMessage(System.Net.HttpStatusCode.PartialContent) { Content = new StringContent("Updated") }; return(Task.FromResult(response)); } catch (System.Exception ex) { string message = ex.InnerException != null ? ex.InnerException.Message : ex.Message; throw new Gale.Exception.GaleException("API_DB_ERROR", message); } } //------------------------------------------------------------------------------------- }
public override Task <HttpResponseMessage> ExecuteAsync(System.Threading.CancellationToken cancellationToken) { var table_type = typeof(TModel); string table_name = table_type.Name; string primaryKey_name = null; #region FIND PRIMARY KEY var fieldProperties = typeof(TModel).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(System.Data.Linq.Mapping.ColumnAttribute))).ToList(); foreach (System.Reflection.PropertyInfo property in fieldProperties) { string db_name = property.Name; var attr = property.TryGetAttribute <System.Data.Linq.Mapping.ColumnAttribute>(); if (attr != null) { System.Data.Linq.Mapping.ColumnAttribute column_attr = (attr as System.Data.Linq.Mapping.ColumnAttribute); if (column_attr != null && column_attr.Name != null && column_attr.Name.Length > 0) { db_name = column_attr.Name; if (column_attr.IsPrimaryKey) { primaryKey_name = db_name; break; } } } } #endregion var table_attr = table_type.TryGetAttribute <System.Data.Linq.Mapping.TableAttribute>(); if (table_attr != null && table_attr.Name != null && table_attr.Name.Length > 0) { table_name = table_attr.Name; } #region SQL Builder System.Text.StringBuilder builder = new StringBuilder(); builder.AppendFormat("DELETE FROM {0} ", table_name); builder.AppendFormat(" WHERE"); builder.AppendFormat(" {0} = '{1}'", primaryKey_name, this.id); string query = builder.ToString(); #endregion //------------------------------------------------------------------------------------- //---[ DATABASE CALL using (Gale.Db.DataService svc = new Gale.Db.DataService(query)) { try { //Create the repository this.ExecuteSql(svc); HttpResponseMessage response = new HttpResponseMessage(System.Net.HttpStatusCode.OK) { Content = new StringContent("Deleted") }; return(Task.FromResult(response)); } catch (System.Exception ex) { string message = ex.InnerException != null ? ex.InnerException.Message : ex.Message; throw new Gale.Exception.GaleException("API_DB_ERROR", message); } } //------------------------------------------------------------------------------------- }
/// <summary> /// Fill a T model with the Database Result Values /// </summary> /// <typeparam name="T">Type to fill</typeparam> /// <param name="model">Entity Table to Fill</param> /// <param name="table">DB Result Table</param> private void FillEntity <T>(ref Gale.Db.EntityTable <T> model, System.Data.DataTable table) { Type EntityType = typeof(T); //Perform Pattern For Huge Data =) List <MemoryFieldCaching> MemoryOptimizer = (from t in EntityType.GetProperties() where t.CanRead && t.GetIndexParameters().Count() == 0 && (t.PropertyType.IsGenericType == false || (t.PropertyType.IsGenericType == true && t.PropertyType.GetGenericTypeDefinition() != typeof(System.Data.Linq.EntitySet <>))) select new MemoryFieldCaching { columnName = t.Name, property = t }).ToList(); foreach (System.Data.DataRow row in table.Rows) { T Item = Activator.CreateInstance <T>(); #region Transform Each Row foreach (MemoryFieldCaching Caching in MemoryOptimizer) { //Perform Pattern For Huge Data =) //Ordinal: // -1: Significa que tiene que ir a buscarlo string Name = ""; if (Caching.ordinal == -1) { try { Name = Caching.columnName; System.Data.Linq.Mapping.ColumnAttribute ColumnAttribute = (System.Data.Linq.Mapping.ColumnAttribute)(Caching.property.GetCustomAttributes(typeof(System.Data.Linq.Mapping.ColumnAttribute), true).FirstOrDefault()); if (ColumnAttribute != null && ColumnAttribute.Name != null && ColumnAttribute.Name.Length > 0) { Name = ColumnAttribute.Name; } if (ColumnAttribute == null) { Caching.ordinal = -2; //Campo Personalizado (no debe ser llenado por base de datos) } else { if (ColumnAttribute != null) { //Si existe el atributo de columna y puede ser nulo, verifico que esta columna exista, de no existir esta columna, //no se debe caer, sino que solo no debe establecerla if (ColumnAttribute.CanBeNull || ColumnAttribute.DbType == null) { if (table.Columns.Contains(Name)) { Caching.ordinal = table.Columns[Name].Ordinal; } else { Caching.ordinal = -2; } } else { try { if (table.Columns.Contains(Name)) { Caching.ordinal = table.Columns[Name].Ordinal; } else { Caching.ordinal = -2; } } catch (System.Exception ex) { //throw new Gale.Gale.Exception.GaleException("ColumnNameNotFoundInDataServiceAndIsNotNullable", Caching.columnName, Name, EntityType.Name); throw ex; } } } else { Caching.ordinal = table.Columns[Name].Ordinal; } } } catch (System.Exception ex) { //---[ Guard Exception ]------------------------------------------------------------------------------------------------------- Gale.Exception.GaleException.Guard(() => ex is IndexOutOfRangeException, "ColumnNameNotFoundInDataService", Caching.columnName, Name, EntityType.Name); //----------------------------------------------------------------------------------------------------------------------------- throw ex; } } if (Caching.ordinal != -2) { object data = row[Caching.ordinal]; if (data is DateTime) { data = DateTime.SpecifyKind((DateTime)data, DateTimeKind.Local); } if (data is System.Guid && Caching.property.PropertyType == typeof(String)) { data = data.ToString(); } if (!(data is System.DBNull)) { //Parse AnyWay for implicit Casting if (Caching.property.PropertyType.IsGenericType == false && Caching.property.PropertyType != data.GetType()) { data = Convert.ChangeType(data, Caching.property.PropertyType); } Caching.property.SetValue(Item, data, null); } } } #endregion model.Add(Item); } }