I have two classes that have composite primary keys, for example:
Cliente
:
public class Cliente
{
public int EscritorioId { get; set; }
public virtual Escritorio Escritorio { get; set; }
public int Id { get; set; }
}
public class ClienteMapping : EntityTypeConfiguration<Cliente>
{
public ClienteMapping()
{
HasKey(x => new { x.Id, x.EscritorioId });
}
}
Documento
:
public class Documento
{
public int EscritorioId { get; set; }
public virtual Escritorio Escritorio { get; set; }
public int Id { get; set; }
public virtual ICollection<Cliente> ClientesComAcesso { get; set; }
}
And in the mapping of class Documento
I have a NxN mapping :
public class DocumentoMapping: EntityTypeConfiguration<Documento>
{
public DocumentoMapping()
{
HasKey(x => new { x.EscritorioId, x.Id });
HasMany(x => x.Clientes)
.WithMany()
.Map(m =>
{
x.MapLeftKey("EscritorioId", "DocumentoId");
x.MapLeftKey("EscritorioId", "ClienteId");
x.ToTable("DocumentoClientes");
});
}
}
Because a customer can be a recipient / access to multiple documents.
However, when trying to generate the Migrations file for this case I get the following error:
The specified association foreign key columns 'DocumentId' are invalid. The number of columns specified must match the number of primary key columns.
Trying to rename composite keys such as Documento_EscritorioId
and Cliente_EscritorioId
, for example:
HasMany(x => x.Clientes)
.WithMany()
.Map(m =>
{
x.MapLeftKey("Documento_EscritorioId", "DocumentoId");
x.MapLeftKey("Cliente_EscritorioId", "ClienteId");
x.ToTable("DocumentoClientes");
});
It works, but in this case we have a redundancy.
What is the correct way to do this mapping?