private List<AssociationModel> BuildAssociations(DAL dal) { var associations = new List<AssociationModel>(); foreach (var rawAssociation in dal.GetRawAssociations()) { var association = new AssociationModel(); association.PrimaryTable = db.Tables.Single(t => t.Name.Equals(rawAssociation.Item2)); association.ForeignTable = db.Tables.Single(t => t.Name.Equals(rawAssociation.Item1)); association.PrimaryColumn = association.PrimaryTable.Columns.Single(c => c.Name.EqualsIgnoreCase(dal.GetPrimaryColumnName(association))); association.ForeignColumn = association.ForeignTable.Columns.Single(c => c.Name.EqualsIgnoreCase(dal.GetForeignColumnName(association))); association.ForeignTable.ForeignKeys.Add(association.ForeignColumn); association.Type = AssociationType.OneToMany; associations.Add(association); } return associations; }
private void SetManyToMany(List<AssociationModel> associations) { var possibleJoinTables = db.Tables.Where(t => t.Columns.Count < 3 || (t.Columns.Count < 4 && t.Columns.Any(c => c.Name.EqualsIgnoreCase("id")))); foreach (var table in possibleJoinTables) { var associationsInQuestion = associations.Where(a => a.ForeignTable.Equals(table)).ToList(); if (associationsInQuestion.Count() > 1) { if (Program.CallResponse(string.Format("Is {0} a join table that should not appear in the model? (y/n)", table.Name)).EqualsIgnoreCase("y")) { var newAssociation = new AssociationModel() { Type = AssociationType.ManyToMany }; newAssociation.PrimaryTable = associationsInQuestion[0].PrimaryTable.Equals(table) ? associationsInQuestion[0].ForeignTable : associationsInQuestion[0].PrimaryTable; newAssociation.ForeignTable = associationsInQuestion[1].PrimaryTable.Equals(table) ? associationsInQuestion[1].ForeignTable : associationsInQuestion[1].PrimaryTable; table.JoinOnly = true; using (var dal = new DAL(connectionString)) { newAssociation.ForeignColumn = table.Columns.Single(c => c.Name.EqualsIgnoreCase(dal.GetForeignColumnName(newAssociation.ForeignTable, table))); newAssociation.PrimaryColumn = table.Columns.Single(c => c.Name.EqualsIgnoreCase(dal.GetForeignColumnName(newAssociation.PrimaryTable, table))); } newAssociation.JoinTable = table; associationsInQuestion.ForEach(aiq => associations.Remove(aiq)); associations.Add(newAssociation); } } } }