Update records linked with Entity Framework?

-2

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

Let's suppose I have two people registered at the bank:

  

PersonId: 1, Name: João, PessoaConjugeId = null

     

PersonId: 2, Name: Maria, PersonaConjugeId = null

I want it when updating joan like this:

  

PersonId: 1, Name: João, PessoaConjugeId = 2

Automatically, Maria will look like this:

  

PersonId: 2, Name: Maria, PersonaConjugeId = 1

After a while, John can go back to being single and back to the initial state:

  

PersonId: 1, Name: João, PessoaConjugeId = null

With this Maria must also return to the initial state:

  

PersonId: 2, Name: Maria, PersonaConjugeId = null

I would like to know if the entity framework has any configuration that automates this update process, if there is no 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;
}
    
asked by anonymous 27.11.2017 / 18:25

1 answer

0

As said by LINQ , it really is a modeling error and you should have a middle table.

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

    
07.12.2017 / 11:55