The department providing a service is one thing. A department taking a service is another. You are treating two different things as the same thing. By 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 another’s service, I believe there must be one Model separately 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, ensures the uniqueness of the associative record. Additional validations may be required in the application to avoid strange key duplicity errors 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 that they are related to a RequisicaoServico
, that is to say:
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; }
}
is using
Fluent API
?– Maicon Carraro
Yes, I am, effluent.
– Stefano Sandes