1
I’m starting out in the Entity Framework and when trying to load a State entity, the related Parent entity is coming with null value, which I could adjust in my code to resolve?
State class:
public class Estado
{
...
public int Id { get; set; }
public string Nome { get; set; }
public Pais Pais { get; set; }
}
Pais Class:
public class Pais
{
...
public int Id { get; set; }
public string Nome { get; set; }
}
Mapping State:
public class EstadoConfiguracao: EntityTypeConfiguration<Estado>
{
public EstadoConfiguracao()
{
HasKey(e => e.Id);
Property(e => e.Nome).HasColumnName("Nome").HasMaxLength(50).IsRequired();
ToTable("estado");
HasRequired(e => e.Pais).WithRequiredPrincipal();
}
}
Mapping Pais:
public class PaisConfiguracao: EntityTypeConfiguration<Pais>
{
public PaisConfiguracao()
{
HasKey(p => p.Id);
Property(p => p.Nome).HasColumnName("Nome").HasMaxLength(50).IsRequired();
ToTable("pais");
}
}
I am creating a method to receive the Id of a State as parameter and return the State with the Country:
public Estado ObterComPais(Int32 id)
{
return _context.Set<Estado>().Include(e => e.Pais).SingleOrDefault(e => e.Id == id);
}