I have three simple classes of city, state and country. I noticed that simply declaring a property of type Estado
in class Cidade
the foreign key is generated correctly. I would like to know how to do these mappings in the hand, I am safer, and if my concern is for nothing, there is doubt about the need to have mapping options in hand.
Here are the entities:
public class CidadeEntity {
public int Id { get; set; }
public string Nome { get; set; }
//public int EstadoId { get; set; }
public virtual EstadoEntity Estado { get; set; }
}
public class EstadoEntity{
public int Id { get; set; }
public string Sigla { get; set; }
public string Nome { get; set; }
public virtual IList<CidadeEntity> CidadeLista { get; set; }
//public byte EstadoPaisId { get; set; }
public virtual PaisEntity Pais { get; set; }
}
public class PaisEntity {
public int Id { get; set; }
public string Sigla { get; set; }
public string Nome { get; set; }
public virtual IList<EstadoEntity> EstadoLista { get; set; }
}
My mappings:
public CidadeMap() {
ToTable("Cidade");
HasKey(c => c.Id);
Property(p => p.Nome)
.IsRequired()
.HasColumnType("varchar")
.HasMaxLength(120);
//HasRequired(f => f.Estado).WithMany(p => p.CidadeLista).HasForeignKey(p => p.EstadoId);
}
public EstadoMap() {
ToTable("Estado");
HasKey(c => c.Id);
Property(p => p.Sigla).IsRequired().HasColumnType("char").HasMaxLength(5);
Property(p => p.Nome).IsRequired().HasColumnType("varchar").HasMaxLength(75);
//Ignore(p => p.EstadoPaisId);
//Relacionamentos
HasRequired(p => p.CidadeLista).WithRequiredPrincipal().Map(p => p.MapKey("EstadoId"));
}
public PaisMap() {
ToTable("Pais");
HasKey(c => c.Id);
Property(p => p.Sigla)
.HasColumnType("varchar")
.HasMaxLength(5);
Property(p => p.Nome)
.HasColumnType("varchar")
.HasMaxLength(50);
}
Context with DB:
[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
public class DataContext:DbContext {
public DataContext():base("ConexaoBD") {
}
public DbSet<PaisEntity> Pais { get; set; }
public DbSet<EstadoEntity> Estado { get; set; }
public DbSet<CidadeEntity> Cidade { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Configurations.Add(new PaisMap());
modelBuilder.Configurations.Add(new EstadoMap());
modelBuilder.Configurations.Add(new CidadeMap());
base.OnModelCreating(modelBuilder);
}
}
I did the% mapping with EstadoMap
( Cidade
) but it was duplicated because it generated mine and the automatic mapping (this without HasRequired(p => p.CidadeLista).WithRequiredPrincipal().Map(p => p.MapKey("EstadoId"))
), I can see that mapping by the city also ( nullable: false
), but it did not work and I did not realize if there is a difference between the State and the City. I do not know if I'm doing things right.