Uploading an entity Country related to State

1

I'm starting in the Entity Framework and when trying to load an entity state, the relational parent entity is coming with null value, what could I adjust in my code to solve?

Class Status:

public class Estado
{
   ...
   public int Id { get; set; }
   public string Nome { get; set; }
   public Pais Pais { get; set; }
}

Country Class:

public class Pais
{
   ...
   public int Id { get; set; }
   public string Nome { get; set; }
}

Mapping Status:

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

Country Mapping:

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

    
asked by anonymous 14.01.2016 / 20:25

1 answer

1

Using exactly the question code I got.

This is the first time I've used Toad for Mysql .

I noticed that there were two versions of it on the PC: a 7.3 another 7.7 (and until then I was using the older one without realizing it).

I removed the tables and circled my script to re-create the DB because I was finding this situation very strange. When rebuilding the DB and now using Toad for Mysql in the newer version (7.7) I succeeded.

Then, with the above code I was able to load a Country entity 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:

Changed Country Class:

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

After 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 one-to-many relationship, where a country has many states.

    
15.01.2016 / 20:48