The department providing a service is one thing. One department taking one service is another. You are treating two different things as one. For your explanation, what we have is:
public class Departamento
{
[Key]
public int DepartamentoId { get; set; }
...
public virtual ICollection<Servico> Servicos { get; set; }
}
public class Servico
{
[Key]
public int ServicoId { get; set; }
public int DepartamentoId { get; set; }
...
public virtual Departamento Departamento { get; set; }
}
If one department is requesting a service from another, I believe there should be a separate Model for this. For example:
public class RequisicaoServico
{
[Key]
public int RequisicaoServicoId { get; set; }
[Index("IUQ_RequisicaoServico_ServicoId_DepartamentoId", IsUnique = true, Order = 1)]
public int ServicoId { get; set; }
[Index("IUQ_RequisicaoServico_ServicoId_DepartamentoId", IsUnique = true, Order = 2)]
public int DepartamentoId { get; set; }
[Required]
public DateTime DataRequisicao { get; set; }
[Required]
public Boolean Finalizado { get; set; }
[DataType(DataType.MultilineText)]
[Required]
public String Descricao { get; set; }
public virtual Departamento Departamento { get; set; }
public virtual Servico Servico { get; set; }
}
[Index]
, introduced in this form from the Entity Framework 6.1.0, guarantees the uniqueness of the associative register. Additional validations may be required in the application to avoid extraneous errors of key duplication for the user.
Being the associative table, the only thing you would need to do now is to update the Models of Departamento
and Servico
to admit to be related to RequisicaoServico
, ie: p>
public class Departamento
{
[Key]
public int DepartamentoId { get; set; }
...
public virtual ICollection<Servico> Servicos { get; set; }
public virtual ICollection<RequisicaoServico> RequisicoesServicos { get; set; }
}
public class Servico
{
[Key]
public int ServicoId { get; set; }
public int DepartamentoId { get; set; }
...
public virtual Departamento Departamento { get; set; }
public virtual ICollection<RequisicaoServico> RequisicoesServicos { get; set; }
}