Inserting and updating data in N-N tables (many to many)

Asked

Viewed 278 times

2

I’m having trouble saving in a relationship of many to many, follows my model:

public class Pessoa
{
    public int id { get; set; }
    public string descricao { get; set; }
    public ICollection<Conta> Conta { get; set; }
}


public class Conta
{
    public int id { get; set; }
    public string descricao { get; set; }
    public ICollection<Pessoa> Pessoa { get; set; }
}

Here is the setting in my context for n-n:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Pessoa>()
        .HasMany<Conta>(x => x.Conta)
        .WithMany(x => x.Pessa)
        .Map(x =>
        {
            x.ToTable("PessoaConta");
            x.MapLeftKey("pessoaId");
            x.MapRightKey("contaId");
        });
    base.OnModelCreating(modelBuilder);
}

So far so good: my scheme of Migrations works perfectly, but would like to know when to save the data in the table pessoa and table conta already insert the respective values in the table pessoaConta. From now on I thank you all.

1 answer

3


As Collections need to be virtual. Also try using plural names:

public virtual ICollection<Conta> Contas { get; set; }
public virtual ICollection<Pessoa> Pessoas { get; set; }

Run some tests:

var fulano = new Pessoa { descricao = "Fulano" };
var beltrano = new Pessoa { descricao = "Beltrano" };
var sicrano = new Pessoa { descricao = "Sicrano" };

context.Pessoas.Add(fulano);
context.Pessoas.Add(beltrano);
context.Pessoas.Add(sicrano);

context.SaveChanges();

var conta = new Conta { descricao = "Conta Coletiva" };
conta.Pessoas = new List<Pessoa> { fulano, beltrano, sicrano };
context.Contas.Add(conta);

context.SaveChanges();
  • solved temporarily, but the following problem appeared. it would be possible when you already have the account and the registered person to link the data in table N-N

  • There you have to map manual. See more here.

Browser other questions tagged

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