0
I am unable to change a foreingkey field in the database. In my case, the objects (Typoendereco = 3 and Address = 2) already exist.
Follows the model (simple):
public class Endereco
{
public int Id { get; set; }
public string Cep { get; set; }
public string Logradouro { get; set; }
public string Bairro { get; set; }
public string Cidade { get; set; }
public string Uf { get; set; }
public TipoEndereco Tipo { get; set; }
}
public class TipoEndereco
{
public int Id { get; set; }
public string Nome { get; set; }
}
I am changing the address data as follows:
TipoEnderecoBLO teblo = new TipoEnderecoBLO();
EnderecoBLO eblo = new EnderecoBLO();
TipoEndereco te = new TipoEndereco();
te.Id = 3;
Endereco e = new Endereco();
e.Bairro = "Casa Grande";
e.Cep = "22.723-002";
e.Cidade = "Rio de Janeiro";
e.Logradouro = "Estrada do Mapuá";
e.Uf = "RJ";
e.Tipo = te;//aqui estou mudando o tipo de endereço
e.Id = 2;
eblo.Update(e);
When sending the command:
_context.Entry(endereco).State = EntityState.Modified;
_context.SaveChanges();
Some address data is changed, but the address type (Tipo_id) is not changed in the database.
Can someone help me?
Hello again Gypsy, First, thank you so much for helping me! I made the following change: _context.TipoEndereco.Attach(address.Type); _context.Entry(address). State = Entitystate.Modified; _context.Savechanges(); Makes sense?
– Leandro Duarte
Yes, but I’ll need to update my answer.
– Leonel Sanches da Silva
Look now. It should work perfectly this way.
– Leonel Sanches da Silva
Gypsy, It worked perfectly! I’d like to ask you a question: Why did I have to bring the database address? So I can create a context? I say this because I am using an app console and for classes that have no relationship, I did not need to search them in the same database I searched for address. Thank you,
– Leandro Duarte
The Entity Framework uses what we call the Observer Context: it only synchronizes with the database the entities that we attach to the context, either by search or by attachment, as I explained. All this I speak in my course, if interested.
– Leonel Sanches da Silva
I’m already there. Looking for vacancies for 2017...rs
– Leandro Duarte
Just call me here. I take individual lessons too.
– Leonel Sanches da Silva