Primary key composed with entities in the Entity Framework

2

I need to make a composite primary key relationship in the entity framework using the entities themselves.

 public class ProjetoDocumento
{ 
    public Projeto Projeto { get; set; }
    public Documento Documento { get; set; }
}
    
asked by anonymous 13.03.2015 / 04:27

1 answer

3

It would be a classical associative entity, not necessarily a composite key case. Do 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; }
}

In addition, update your Projeto and Documento entities:

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

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

Or you can still use the Fluent API to configure, in the 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 look like this:

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

public class Documento
{
    ...
    public virtual ICollection<Projeto> Projetos { get; set; }
}
    
13.03.2015 / 04:35