0
Next, I’m working on a new project Asp.net-mvc, and I have 3 classes.
public class Anuncio
{
public int AnuncioID { get; set; }
public string UsuarioID { get; set; }
[Required]
[MaxLength(255)]
[Display(Name="Título")]
public string Titulo { get; set; }
[Required]
[MaxLength(2000)]
[Display(Name="Descrição")]
public string Descricao { get; set; }
[Display(Name="Data do anúncio")]
public DateTime DataAnunciado { get; set; }
public Contato Contato { get; set; }
[Display(Name="Endereço")]
public Endereco Endereco { get; set; }
public TipoCategoria Categoria { get; set; }
public ICollection<Imagem> Imagens { get; set; }
}
public class Endereco
{
[Key]
public int EnderecoID { get; set; }
[Required]
public Estado Estado { get; set; }
[Required,Display(Name="Município")]
public Municipio Municipio { get; set; }
public string Bairro { get; set; }
public string Rua { get; set; }
[Display(Name="Número")]
public string Numero { get; set; }
public string Cep { get; set; }
public string Complemento { get; set; }
}
public class Estado
{
[Key]
public int EstadoID { get; set; }
public string Nome { get; set; }
public string Sigla { get; set; }
}
So, as you may notice, Anuncio
has 1 Endereco
, which in turn has 1 Estado
.
After I run the application, I include the states, so for example, I have a Estado
with EstadoID = 1, Nome = Paraná, Sigla = PR
.
When I’m gonna register a new one Anuncio
, even defining the instance of Estado
on the bench at Anuncio
, for example:
public ActionResult NovoAnuncio(Anuncio anuncio)
{
if (ModelState.IsValid)
{
Estado estado = db.Estado.Find(1);
anuncio.Endereco.Estado = estado;
db.Anuncio.Add(anuncio);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
return View(anuncio);
}
It CREATES another record in the BD.
Why he does not reference the State already registered in the comic?
The "Endereco" object is being populated from where? from what I see the method only receives "Anuncio", you need an instance of "Endereco" to popular power the attribute "Estado".
– Tuyoshi Vinicius
Check how the Address instance is in the Ad, if you are not inserting a new one either.
– user3628
So gentlemen, this Address, is always a new one, the user registers the address in the View, then comes an Announcement object, already with instantiated and populated Address, I only know the state to enter it.
– Ivan Ricardo Lopes