public void AddFK(string table, string field, string targetTable) { if (!ForeignKeys.ContainsKey(table)) { ForeignKeys.Add(table, new Dictionary <string, string>()); } if (!ForeignKeys[table].ContainsKey(field)) { ForeignKeys[table].Add(field, targetTable); } }
/// <summary> /// Returns the string representation of this EntityType. /// </summary> /// <returns>Returns the string representation of this EntityType.</returns> public override string ToString() { StringBuilder stringBuilder = new StringBuilder("[EntityStructure: " + Name + "]\n"); foreach (var attribute in Attributes) { stringBuilder.Append(" - "); if (PrimaryKeys.Contains(attribute.Key)) { stringBuilder.Append("[PK] "); } stringBuilder.Append(attribute.Key + " (" + attribute.Value + ") "); if (ForeignKeys.ContainsKey(attribute.Key)) { stringBuilder.Append("[FK references " + ForeignKeys[attribute.Key].EntityName + "(" + ForeignKeys[attribute.Key].KeyName + ")" + "]"); } stringBuilder.Append("\n"); } if (BelongsToMany.Any()) { stringBuilder.Append(" + BelongsToMany ("); foreach (var item in BelongsToMany) { stringBuilder.Append(item).Append(" "); } stringBuilder.Append(")\n"); } return(stringBuilder.ToString()); }
public virtual Command CreateCommand(bool insert) { string commandText = ""; Command command = connection.CreateCommand(); command.Transaction = transaction; string[] fields; string[] values; //aqui iremos determinar quais os objetos que irão compor este comando TableDefinitionAttribute tableDefinition = currentType.GetCustomAttributes(typeof(TableDefinitionAttribute), false)[0] as TableDefinitionAttribute; commandText += "{command} {tablename} {command2};"; //aqui não podemos filtrar as propriedades apenas pela instancia, pois as mesmas podem vir de heranças var props = currentType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(p => { //--------------------------------------------------------------------------- // garantir que apenas os campos desta tabela sejam passadas como propriedade // Podem estar vindo de uma herança //--------------------------------------------------------------------------- string fieldName = GetFieldName(p, tableDefinition, false); return(tableDefinition.Fields.Contains(fieldName)); }); if (BeforeCreateCommandAction != null) { BeforeCreateCommandAction(command); } #region Campos foreach (var item in props) { if (CanUseField(item, tableDefinition)) { command.Parameters.Add(CreateParameter(tableDefinition, item, insert)); } } #endregion #region Default Values IList <DefaultValueAttribute> defaultValues = (from x in currentType.GetCustomAttributes(typeof(DefaultValueAttribute), false) select x as DefaultValueAttribute).ToList <DefaultValueAttribute>(); if (defaultValues.Count > 0) { foreach (DefaultValueAttribute defaultValue in defaultValues) { command.Parameters.Add(CreateParameter(defaultValue.FieldName, "@" + defaultValue.FieldName, defaultValue.Value, insert)); } } #endregion #region chaves estrangeiras //na nossa aplicação usamos o GUID como pk e sempre temos ter as chaves estrangeiras que serão do tipo inteiro //recuperar a fk ForeignKeyAttribute[] fks = GetForeignKey(); //para cada um retornado, temos que validar se existe na definição if (fks != null) { foreach (ForeignKeyAttribute fk in fks.Where(f => //--------------------------------------------------------------------------- // garantir que apenas os campos desta tabela sejam passadas como propriedade // Podem estar vindo de uma herança //--------------------------------------------------------------------------- tableDefinition.Fields.Contains(f.ForeignKey) && foreignKeys.ContainsKey(f.TableName))) { string fieldName = fk.ForeignKey; string parameterName = "@" + fk.ForeignKey; object value = foreignKeys[fk.TableName]; command.Parameters.Add(CreateParameter(fieldName, parameterName, value, insert)); } } #endregion #region fields/ values fields = new string[command.Parameters.Count]; values = new string[command.Parameters.Count]; #endregion #region insert if (insert) { for (int i = 0; i < command.Parameters.Count; i++) { fields[i] = command.Parameters[i].SourceColumn; values[i] = command.Parameters[i].ParameterName; } commandText = commandText .Replace("{command}", "INSERT INTO") .Replace("{command2}", "(" + fields.Join() + ") VALUES (" + values.Join() + ")") .Replace("{tablename}", tableDefinition.TableName.ToLower()); } #endregion #region update else { for (int i = 0; i < command.Parameters.Count; i++) { fields[i] = String.Format("{0} = {1}", command.Parameters[i].SourceColumn, command.Parameters[i].ParameterName); } commandText = "UPDATE {0} SET {1} WHERE {2}"; commandText = string.Format(commandText, tableDefinition.TableName, fields.Join(), GetUpdateWhere(command, Utilities.DbUtils.GetPrimaryKeyValue(model))); } #endregion command.CommandText = commandText; return(command); }
/// <summary> /// Indicates whether the given <paramref name="attribute"/> is a foreign key. /// </summary> /// <param name="attribute">The attribute name.</param> /// <returns>True, if the attribute is a foreign key, otherwise false.</returns> public bool IsForeignKey(string attribute) { return(ForeignKeys.ContainsKey(attribute)); }