Persistence using Fluent API

4

How do I persist an address without having to pass all client information?

Below is my address client mapping:

HasMany(f => f.EnderecoList)
            .WithMany(e => e.ClienteList)
            .Map(me =>
            {
                me.MapLeftKey("ClienteId");
                me.MapRightKey("EnderecoId");
                me.ToTable("EnderecosCliente");
            });
    
asked by anonymous 28.09.2015 / 18:13

2 answers

2

Ideally, you should not use the Fluent API , but rather an associative entity:

public class Cliente
{
    /* Propriedades do Cliente */

    public virtual EnderecoCliente EnderecoCliente { get; set; }
}

public class Endereco
{
    /* Propriedades do Endereco */

    public virtual EnderecoCliente EnderecoCliente { get; set; }
}

And then:

public class EnderecoCliente 
{
    [Key]
    public int EnderecoClienteId { get; set; }
    [Index("IUQ_EnderecoCliente_ClienteId_EnderecoId", IsUnique = true, Order = 1)]
    public int ClienteId { get; set; }
    [Index("IUQ_EnderecoCliente_ClienteId_EnderecoId", IsUnique = true, Order = 2)]
    public int EnderecoId { get; set; }

    public virtual Endereco Endereco { get; set; }
    public virtual Cliente Cliente { get; set; }
}

Defining:

var endereco = new Endereco 
{
    /* Defina aqui outras propriedades */
    EnderecoCliente = new EnderecoCliente {
        Cliente = contexto.Clientes.FirstOrDefault(c => c.ClienteId == 5)
    }
};

[Index] , introduced in this form from the Entity Framework 6.1.0, guarantees the uniqueness of the associative register. Additional validations may be required in the application to avoid extraneous errors of key duplication for the user.

    
28.09.2015 / 18:22
1

The way you're mapping is a many-to-many relationship ... if you want a client to have multiple addresses try something like this:

    public class ClienteEntity
{
    [Key]
    public int Codigo { get; set; }
    public string Nome { get; set; }
    public virtual HashSet<EnderecoEntity> Enderecos { get; set; }
}

public class EnderecoEntity
{
    [Key]
    public int Codigo { get; set; }
    public string Logradouro { get; set; }

    public int? CodigoCliente { get; set; }
    public virtual ClienteEntity Cliente { get; set; }
}

public class ClienteContext:DbContext
{
    public DbSet<ClienteEntity> Clientes { get; set; }
    public DbSet<EnderecoEntity> Enderecos { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder
            .Entity<ClienteEntity>()
            .HasMany(t=>t.Enderecos)
            .WithOptional(c=>c.Cliente)
            .HasForeignKey(c=>c.CodigoCliente);
    }
}

With this you can populate multiple addresses with a client and get from the address on the corresponding client ...

    
28.09.2015 / 19:25