I'm reviewing some programming approaches and fall into a dilemma as to where we should instantiate our navigation properties from EF
ICollection
.
Many cases I see that the personnel instantiates them in the constructor, would this be a good practice?
In a few cases I see instances that instantiate only when really necessary, which I think would be a more correct approach.
So, taking the example of the Pais
entity that has a list of Estados
Parent Entity
[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 constructor the creation of a HashSet
public Pais()
{
Estados = new HashSet<Estado>();
}
In another approach I see only at the time of use, as shown in 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 this second case, if the ICollection<Estado>
creation was in the Pais
entity, you would not need the if
to check if the Estados
object is null by simply adding more items in the collection. / p>