Update records linked with Entity Framework?

Asked

Viewed 258 times

-2

For example I have a person class and every person can have a spouse if she wants to (Optional).

Suppose I have two people registered at the bank:

Personal: 1, Name: John, Personal = null

Personal: 2, Name: Maria, Personal = null

I want when upgrade john like this:

Personal: 1, Name: John, Personal = 2

Automatically the maria is like this:

Personal: 2, Name: Mary, Personal = 1

After a while João can return to being single and return to the initial state:

Personal: 1, Name: John, Personal = null

With this Mary must also return to the initial state:

Personal: 2, Name: Maria, Personal = null

I wonder if the Entity framework has some configuration that Automatizes this update process, if there is not what would be the best way to perform this update process?

//Classe Pessoa
public class PessoaModel
{
    public int? PessoaId { get; set; }
    public string Nome { get; set; }

    public int? PessoaConjugeId { get; set; }
    public virtual PessoaModel PessoaConjuge { get; set; }    
}

//Fluent API
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<UsuarioModel>()
        .HasOptional(c => c.UsuarioConjuge)
        .WithMany()
        .HasForeignKey(c => c.UsuarioConjugeId);
}

//Metodo que atualiza
public UsuarioModel Atualizar(UsuarioModel model)
{
    MeuSistemaContext db = new MeuSistemaContext();

    if (db.Entry(model).State == EntityState.Detached)
    {
        db.Set<UsuarioModel>().Attach(model);
    }

    db.Entry(model).State = EntityState.Modified;
    db.SaveChanges();
    return model;
}
  • It seems to me a modeling error. If one table depends on updating the other you should use an intermediate table for this.

  • Can post an example code of how I should do, I was here right now trying to do and noticed that when I do: var lstPessoa = db.TbPessoa.Tolist(); and cliko no + da lstPessoa by visual studio to navigate the properties he hangs the visual studio, I believe it must be in infinite loop.

  • Thank you, I appreciate it. Meanwhile I’ll see here if I get somewhere rsrs

1 answer

0

As said the LINQ, really is a mistake in modeling and you should have an intermediate table.

In a common system, without EF, you could create a Rigger in the Person table update to change the spouse.

Browser other questions tagged

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