-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.
– Jéf Bueno
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.
– Mauricio Ferraz
Thank you, I appreciate it. Meanwhile I’ll see here if I get somewhere rsrs
– Mauricio Ferraz