HRRO
HRRO

Reputation: 45

Define two tables in c# with foreign key

I want to make 2 tables : Teams and Projects I want to make a 1 : n relationship between these two. This is my code: //Creare tabela Projects

    public void CreareTabelaProjects() {
        string query = "CREATE TABLE IF NOT EXISTS Projects" + "(" + "id_project MEDIUMINT PRIMARY KEY AUTO_INCREMENT," + "name VARCHAR(30)," +
            "description VARCHAR(30)," + "FOREIGN KEY (team_id) REFERENCES Teams(team_id)" + ");";
        if (this.OpenConnection() == true) {
            MySqlCommand cmd = new MySqlCommand(query, connection);
            cmd.ExecuteNonQuery();
            this.CloseConnection();
        }
    }

   //Creare tabela Teams

    public void CreareTabelaTeams() {
        string query = "CREATE TABLE IF NOT EXISTS Teams" + "(" + "team_id INT AUTO_INCREMENT PRIMARY KEY," + "name VARCHAR(30)" + ");";
        if (this.OpenConnection() == true)
        {
            MySqlCommand cmd = new MySqlCommand(query, connection);
            cmd.ExecuteNonQuery();
            this.CloseConnection();
        }

    }

When i run this, an error occured saying this : Key column 'team_id' doesn't exist in table. The application creates only the Team table. Any help please? Thanks!

Upvotes: 0

Views: 1088

Answers (2)

HRRO
HRRO

Reputation: 45

This is the right query for Project Table

 string query = "CREATE TABLE IF NOT EXISTS Projects" + "(" + "project_id INT AUTO_INCREMENT PRIMARY KEY," + "team_id INT,"+"name VARCHAR(30)," +
            "description VARCHAR(30)," + "FOREIGN KEY (team_id) REFERENCES Teams(team_id)" + ");";

Thanks a lot anyway

Upvotes: 1

D.S.
D.S.

Reputation: 289

Create the second table before the first one

Upvotes: 1

Related Questions