public override IEnumerable <string> SqlCommands() { yield return ($"CREATE TABLE {DbObject.SqlServerName(_modelType)} (\r\n\t" + string.Join(",\r\n\t", CreateTableMembers(false)) + "\r\n)"); }
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); }
public override IEnumerable <string> SqlCommands() { ForeignKeyAttribute fk = _pi.GetForeignKeyAttribute(); string cascadeDelete = (fk.CascadeDelete) ? " ON DELETE CASCADE" : string.Empty; yield return ($"ALTER TABLE {DbObject.SqlServerName(_pi.DeclaringType)} ADD CONSTRAINT [{_pi.ForeignKeyName()}] FOREIGN KEY (\r\n" + $"\t[{_pi.SqlColumnName()}]\r\n" + $") REFERENCES {DbObject.SqlServerName(fk.PrimaryTableType)} (\r\n" + $"\t[{fk.PrimaryTableType.IdentityColumnName()}]\r\n" + ")" + cascadeDelete); }