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