Relationship 1:N using EF using Data Annotationion

Asked

Viewed 23 times

1

I’m trying to map between these two classes, where in championship I have a list of all stages related to the championship

Follows the classes,

[Table("ETAPA")]
public class Etapa
{
    [Key]
    public int Id { get; set; }
    [Column("ETAPA_NUMERO")]
    public int EtapaNumero { get; set; }
    [Column("DATA_EVENTO")]
    public DateTime DataEvento { get; set; }
    [Column("CIDADE")]
    public string Cidade { get; set; }
    [Column("STATUS")]
    public int Status { get; set; }
    [Column("FKID_CAMP")] //minha FK**
    public int IdCamp { get; set; }

    [ForeignKey("IdCamp")]
    public virtual Campeonato Campeonato { get; set; }
}

and the

[Table("CAMPEONATO")]
public class Campeonato
{
    public Campeonato()
    {
        Etapas = new HashSet<Etapa>();                
    }
    [Key]
    [Column("ID")]
    public int Id { get; set; }
    [Column("DESCRICAO")]
    public string Descricao { get; set; }
    [Column("ANO")]
    public int Ano { get; set; }        

    public virtual ICollection<Etapa> Etapas { get; set; }

}

I need to know how to make this relationship using EF 6.0

  • The relationship is already done. There is something that is not working properly?

  • The 'Steps' property is coming null, but there is data in the database

  • What code are you using to get Stages? And Championships?

  • Sorry man !!! , was missing the include on the call, Thank you

1 answer

2


As doubt clarified by comment, there is no problem with the mapping itself, which is correct. When bringing the stages of a championship, it is recommended to rush the load using .Include():

var campeonato = db.Campeonatos
                   .Include(c => c.Etapas)
                   .FirstOrDefault();

Also remove the code below, which is affecting the lazy load:

public Campeonato()
{
    Etapas = new HashSet<Etapa>();                
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.