private IEnumerable <string> CreateTableForeignKeys() { List <string> results = new List <string>(); results.AddRange(_modelType.GetProperties().Where(pi => pi.HasAttribute <Attributes.ForeignKeyAttribute>()) .Select(pi => { var fk = pi.GetCustomAttribute <Attributes.ForeignKeyAttribute>(); return ($@"CONSTRAINT [{pi.ForeignKeyName()}] FOREIGN KEY ( [{pi.SqlColumnName()}] ) REFERENCES {DbObject.SqlServerName(fk.PrimaryTableType)} ( [{nameof(DataRecord<int>.Id)}] )" ); })); results.AddRange(_modelType.GetCustomAttributes <Attributes.ForeignKeyAttribute>() .Where(attr => HasColumnName(_modelType, attr.ColumnName)) .Select(fk => { return ($@"CONSTRAINT [FK_{DbObject.ConstraintName(_modelType)}_{fk.ColumnName}] FOREIGN KEY ( [{fk.ColumnName}] ) REFERENCES {DbObject.SqlServerName(fk.PrimaryTableType)} ( [{nameof(DataRecord<int>.Id)}] )" ); })); return(results); }
private IEnumerable <string> CreateTableUniqueConstraints() { List <string> results = new List <string>(); if (PrimaryKeyColumns(markedOnly: true).Any()) { results.Add($"CONSTRAINT [U_{DbObject.ConstraintName(_modelType)}_Id] UNIQUE ([Id])"); } results.AddRange(_modelType.GetProperties().Where(pi => { var unique = pi.GetCustomAttribute <UniqueKeyAttribute>(); return(unique != null); }).Select(pi => { return($"CONSTRAINT [U_{DbObject.ConstraintName(_modelType)}_{pi.SqlColumnName()}] UNIQUE ([{pi.SqlColumnName()}])"); })); results.AddRange(_modelType.GetCustomAttributes <UniqueKeyAttribute>().Select((u, i) => { string constrainName = (string.IsNullOrEmpty(u.ConstraintName)) ? $"U_{DbObject.ConstraintName(_modelType)}_{i}" : u.ConstraintName; return($"CONSTRAINT [{constrainName}] UNIQUE ({string.Join(", ", u.ColumnNames.Select(col => $"[{col}]"))})"); })); return(results); }
private string CreateTablePrimaryKey() { return($"CONSTRAINT [PK_{DbObject.ConstraintName(_modelType)}] PRIMARY KEY ({string.Join(", ", PrimaryKeyColumns().Select(col => $"[{col}]"))})"); }