3
I have two classes that have composite primary keys, 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 class mapping Documento
I have a mapping Nxn:
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/have access to multiple documents.
However, when trying to generate the Migrations for that case I get the following error:
The specified Association Foreign key Columns 'Documentoid' are invalid. The number of Columns specified must match the number of Primary key Columns.
Trying to give another name to the composite keys, like 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?