Composite primary key with entities in the Entity Framework

Asked

Viewed 1,511 times

2

I need to make a composite primary key relation in the Entity framework using the entities themselves.

 public class ProjetoDocumento
{ 
    public Projeto Projeto { get; set; }
    public Documento Documento { get; set; }
}

1 answer

3

It would be a classical associative entity, not necessarily a composite key case. Do it as follows:

public class ProjetoDocumento
{ 
    [Key]
    public int ProjetoDocumentoId { get; set; }
    public int ProjetoId { get; set; }
    public int DocumentoId { get; set; }

    public virtual Projeto Projeto { get; set; }
    public virtual Documento Documento { get; set; }
}

Additionally, update your entities Projeto and Documento:

public class Projeto
{
    ...
    public virtual ICollection<ProjetoDocumento> ProjetoDocumentos { get; set; }
}

public class Documento
{
    ...
    public virtual ICollection<ProjetoDocumento> ProjetoDocumentos { get; set; }
}

Or you can use the Fluent API to configure, in the event OnModelCreating of your data context:

modelBuilder.Entity<Projeto>()
        .HasMany(p => p.Documentos)
        .WithMany()
        .Map(x =>
        {
            x.MapLeftKey("ProjetoId");
            x.MapRightKey("DocumentoId");
            x.ToTable("ProjetoDocumentos");
        });

However, this approach is much more limited because it does not allow you to expand the associative table.

In this case the classes are like this:

public class Projeto
{
    ...
    public virtual ICollection<Documento> Documentos { get; set; }
}

public class Documento
{
    ...
    public virtual ICollection<Projeto> Projetos { get; set; }
}
  • is that the part of documents is from another project and did not want to leave them tied.

  • A project may have N documents, but a document belongs to only one project?

  • No, but the main issue is that the project does not know the document directly, nor should it. The document project entity extends the project entity by adding this dependency.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.