I'm trying to map the same entity twice in another
public class Conveniado
{
public int Id { get; set; }
public string Nome { get; set; }
[InverseProperty(nameof(ProcedimentoAgregado.ConveniadoDe))]
public virtual ICollection<ProcedimentoAgregado> ProcedimentoAgregadoConveniadosDe { get; set; }
[InverseProperty(nameof(ProcedimentoAgregado.ConveniadoPara))]
public virtual ICollection<ProcedimentoAgregado> ProcedimentoAgregadoConveniadosPara { get; set; }
}
public class Procedimento
{
public int Id { get; set; }
public string Descricao { get; set; }
[InverseProperty(nameof(ProcedimentoAgregado.ProcedimentoDe))]
public virtual ICollection<ProcedimentoAgregado> ProcedimentoAgregadoProcedimentosDe { get; set; }
[InverseProperty(nameof(ProcedimentoAgregado.ProcedimentoPara))]
public virtual ICollection<ProcedimentoAgregado> ProcedimentoAgregadoProcedimentosPara { get; set; }
}
public class ProcedimentoAgregado
{
[Key]
public Guid ProcedimentoAgregadoId { get; set; }
[Display(Name = "Conveniado de")]
public int ConveniadoDeId { get; set; }
[Display(Name = "Procedimento de")]
public int ProcedimentoDeId { get; set; }
[Display(Name = "Conveniado para")]
public int ConveniadoParaId { get; set; }
[Display(Name = "Procedimento para")]
public int ProcedimentoParaId { get; set; }
[ForeignKey(nameof(ConveniadoDeId))]
public virtual Conveniado ConveniadoDe { get; set; }
[ForeignKey(nameof(ConveniadoParaId))]
public virtual Conveniado ConveniadoPara { get; set; }
[ForeignKey(nameof(ProcedimentoDeId))]
public virtual Procedimento ProcedimentoDe { get; set; }
[ForeignKey(nameof(ProcedimentoParaId))]
public virtual Procedimento ProcedimentoPara { get; set; }
}
When running udpate-database
I get the following error
Introducing FOREIGN KEY constraint 'FK_dbo.ProcedureAdded_Dbo.Procedure_ProceduresForId' on table 'ProcedureOgregates' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint or index. See previous errors.
I've always solved this using OnModelCreating
of the context
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ProcedimentoAgregado>()
.HasRequired(a => a.ProcedimentoPara)
.WithMany(a => a.ProcedimentoAgregadoProcedimentosPara)
.HasForeignKey(a => a.ProcedimentoParaId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<ProcedimentoAgregado>()
.HasRequired(a => a.ConveniadoPara)
.WithMany(a => a.ProcedimentoAgregadoConveniadosPara)
.HasForeignKey(a => a.ConveniadoParaId)
.WillCascadeOnDelete(false);
base.OnModelCreating(modelBuilder);
}
Or
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
base.OnModelCreating(modelBuilder);
}
I wonder if you have any other way to solve this without using these two ways?