Map relationships with Fluent API

Asked

Viewed 655 times

1

I have three simple classes of city, state and country. I realized that simply declaring a property of the 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 not, is the doubt of the need to have the options to map in hand.

Follow 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 BD:

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

In the EstadoMap I mapped it with Cidade (HasRequired(p => p.CidadeLista).WithRequiredPrincipal().Map(p => p.MapKey("EstadoId"))) but it was duplicated because it generated mine and automatic mapping (this without nullable: false), I saw that you can do this mapping around the city too (HasRequired(p => p.Estado).WithRequiredDependent();), but it didn’t work out and I didn’t realize if there’s a difference between the State and the City. I don’t know if I’m doing things right.

  • I will prepare an example and already put to you

  • If possible place your Context too

  • I put the context, although it is with Mysql I believe not to make a difference, Caha what does? Thanks for the help

  • Because then, the example I did uses SQL Server, never tested with Mysql, but I believe it should work the same way.

  • 1

    Worked blz :)

1 answer

2


So I made some adaptations mainly in your classes:

Cidademap

I kept

HasRequired(a => a.Estado).WithMany(a => a.CidadeLista).HasForeignKey(a => a.EstadoId);

Estadomap

HasRequired(p => p.CidadeLista).WithRequiredPrincipal().Map(p => p.MapKey("EstadoId"));

I switched to

HasRequired(a => a.Pais).WithMany(a => a.EstadoLista).HasForeignKey(a => a.PaisId);

Cidadeentity

I added

public int EstadoId { get; set; }

Estadoentity

I added

public int PaisId { get; set; }

My context was as follows

public class ExemploContext : DbContext
    {
        public ExemploContext()
            :base("DefaultConnection")
        {

        }

        public DbSet<EstadoEntity> Estados { get; set; }

        public DbSet<CidadeEntity> Cidades { get; set; }

        public DbSet<PaisEntity> Paises { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new EstadoMap());
            modelBuilder.Configurations.Add(new CidadeMap());
            modelBuilder.Configurations.Add(new PaisMap());

            base.OnModelCreating(modelBuilder);
        }
    }

The source code of the example you can get here

I’m not very good with concepts, but in practice the example I gave is how I normally work with mapping relationships in Entityframework using Fluent API

  • It worked here, thanks man, in the tests I ended up thinking that I would not need to declare a property equivalent to the Id of the class "father", then all the tests went wrong.

Browser other questions tagged

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