1
I’m reviewing some programming approaches and falls into a dilemma with regards to where we should instantiate our navigation properties from EF
ICollection
.
Many cases I see that the personal instance them in the builder, this would be a good practice?
In a few cases I see examples that instantiate only when really necessary, which in my view would be a more correct approach.
So, taking the example of the entity Pais
that has a list of Estados
Entidade Pais
[Table("Paises")]
[DisplayColumn("Nome")]
public class Pais : Entidade
{
public Pais()
{
Estados = new HashSet<Estado>();
}
[Key]
public Guid PaisId { get; set; }
[Required]
[StringLength(200)]
public string Nome { get; set; }
[Required]
[StringLength(3)]
public string Sigla { get; set; }
public ICollection<Estado> Estados { get; set; }
}
State entity
[Table("Estados")]
[DisplayColumn("Nome")]
public class Estado : Entidade
{
[Key]
public Guid EstadoId { get; set; }
public Guid PaisId { get; set; }
[Required]
[StringLength(200)]
public String Nome { get; set; }
[Required]
[StringLength(2)]
public String Sigla { get; set; }
public virtual Pais Pais { get; set; }
public ICollection<Cidade> Cidades { get; set; }
}
In the first approach I see in the parent builder the creation of a HashSet
public Pais()
{
Estados = new HashSet<Estado>();
}
In another approach I see only at the time of use, as shown by the following example
pais = new Pais();
if (pais.Estados == null)
pais.Estados = new List<Estado>();
pais.Estados.Add(new Estado() { Sigla = "RS", Nome = "Rio Grande do Sul" });
In the latter case, if the creation of the ICollection<Estado>
were in the entity Pais
, would not need the if
to check whether the object Estados
is null, simply add more items to the collection.
I was going to comment that it was very coincidental to have talked about it and read this question today, rs.
– Jéf Bueno
I thought the questioning was pertinent, so I brought it here
– Pablo Tondolo de Vargas
It sure is. It’s a very good question.
– Jéf Bueno