That’s up to you.
Both ways are right, but I find it really boring to work with composite primary keys, because to reference them by a foreign key, you need both columns. Imagine the chaos to add a new primary column to this table? You will need to add it to all other tables that depend on the old key.
It also takes more work to pass two variables in the client code, so I prefer to do it this way:
CREATE TABLE Projeto_Funcionario (
id INT IDENTITY (1, 1),
idProjeto INT NOT NULL,
idFunc INT NOT NULL,
CONSTRAINT PK_Projeto_Funcionario PRIMARY KEY (id),
CONSTRAINT UNIQUE_Projeto_Funcionario UNIQUE (idProjeto, idFunc),
/* chaves estrangeiras... */
)
With a CONSTRAINT of type UNIQUE, you have the same guarantee of uniqueness that you would have with a primary key, and SQL Server even creates an index for these columns.
Now, when trying to make an INSERT in this table, linking the same employee with the same project, the DBMS will point out CONSTRAINT violation error.
-- esse primeiro insert funciona
INSERT INTO Projeto_Funcionario (idProjeto, idFunc)
VALUES (1, 1)
-- esse não
INSERT INTO Projeto_Funcionario (idProjeto, idFunc)
VALUES (1, 1)
-- erro: Violation of UNIQUE KEY constraint 'UNIQUE_Projeto_Funcionario'. Cannot insert duplicate key in object 'dbo.Projeto_Funcionario'. The duplicate key value is (1, 1).
See working on SQL Fiddle.
They are not composed. They serve as the relationship 1 to N between the table that makes the compound (Project_work) and the normal table (Project or Employee).
– Gabriel Coletta
Yes, I know they are for relationship 1 to N. But I would like to know whether they are composite primary keys or not.
– Renan Narciso
As I said before, they are not composed. If you want there to be only one relationship, use UNIQUE as quoted
– Gabriel Coletta
@Renannarciso, how you creating your model ? could put? the classes.. Fast forward with the Entity Framework, you’ll only have the relationship table in the database, with the two columns being composite primary keys... plus the fields you need.
– Marco Souza
has a very clear example .. http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx
– Marco Souza
Hello @Marconciliosouza I already managed to solve my problem, anyway, thanks! In my associative class.
– Renan Narciso