I have the following class structure, unconventional but it's in the template I need to solve my problem:
Tree:
public class Arvore
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[StringLength(50)]
public string Descricao { get; set; }
public virtual ICollection<Galho_TipoA> Galhos_TipoA { get; set; }
public virtual ICollection<Galho_TipoB> Galhos_TipoB { get; set; }
}
Twig:
public class Galho
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public int ArvoreId { get; set; }
[Required]
[StringLength(50)]
public string Descricao { get; set; }
[ForeignKey("ArvoreId")]
public Arvore Avore { get; set; }
}
public class Galho_TipoA : Galho { }
public class Galho_TipoB : Galho { }
When generating my schema I'm getting the following:
CreateTable(
"dbo.Arvores",
c => new
{
Id = c.Int(nullable: false, identity: true),
Descricao = c.String(nullable: false, maxLength: 50),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Galhos",
c => new
{
Id = c.Int(nullable: false, identity: true),
ArvoreId = c.Int(nullable: false),
Descricao = c.String(nullable: false, maxLength: 50),
Discriminator = c.String(nullable: false, maxLength: 128),
Arvore_Id = c.Int(),
Arvore_Id1 = c.Int(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Arvores", t => t.Arvore_Id)
.ForeignKey("dbo.Arvores", t => t.Arvore_Id1)
.ForeignKey("dbo.Arvores", t => t.ArvoreId, cascadeDelete: true)
.Index(t => t.ArvoreId)
.Index(t => t.Arvore_Id)
.Index(t => t.Arvore_Id1);
Note that several indexes are being generated for Arvore
properties that are of the same type:
.ForeignKey("dbo.Arvores", t => t.Arvore_Id)
.ForeignKey("dbo.Arvores", t => t.Arvore_Id1)
.ForeignKey("dbo.Arvores", t => t.ArvoreId, cascadeDelete: true)
.Index(t => t.ArvoreId)
.Index(t => t.Arvore_Id)
.Index(t => t.Arvore_Id1);
I created the types Galho_TipoA
and Galho_TipoB
exactly to differentiate the records by the Discriminator
field, but it did not work. Instead of pointing to ArvoreId
have created others, one for each property in Arvore
.
How to resolve this issue to ArvoreId
and not have to generate others?
Or, what would be the correct way to structure this schema? p>
Issue
The logic that the model needs to meet is as follows: A Arvore
can have several Galhos
of several types.
So I thought of the types as separate properties.