How to load an entity State-related Parents

Asked

Viewed 159 times

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);
}

inserir a descrição da imagem aqui

1 answer

1


Using exactly the code of the question I got.

It’s the first time I’ve ever worn Toad for Mysql.

I realized I had two versions of it on PC: a 7.3 another 7.7 (and so far I was using the oldest without realizing).

I removed the tables and ran my script to recreate the comic because I was finding this situation very strange. By recreating the BD and now using Toad for Mysql in the newest version (7.7).

So with the above code I was able to load an entity Parents related to State!


Another way to map

Another way to map is by adding a property in Country, which represents a collection/list of States that a Country has:

Class Parents changed:

public class Pais
{
   ...
   public int Id { get; set; }
   public string Nome { get; set; }
   public ICollection<Estado> Estados { get; set; }
}

Then changing the state mapping:

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).WithMany(p => p.Estados).Map(m => m.MapKey("PaisId"));
    }
}

So I was able to map the relationship of one-to-Many, where a country has many states.

Browser other questions tagged

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