Why is the Entity Framework generating a new record in the database? [duplicate]

0

Next, I'm working on a new project , 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; }
}

Then, as you can see, a Anuncio has 1 Endereco , which in turn has 1 Estado .

After running the application, I include the states, so for example, I have a Estado with EstadoID = 1, Nome = Paraná, Sigla = PR .

When I am going to register a new Anuncio , even setting the Estado instance that is in the database in 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 DB.

Why does not it reference the state already registered in the DB?

    
asked by anonymous 01.04.2014 / 19:45

1 answer

1

As I replied in this other question you are loading the record twice in the context and the Entity Framework understands that there are two different records. In your case, this applies to Endereco that does not have a correct reference to Estado .

Modify the following to prevent this:

var estado = db.Estado.Find(1);
anuncio.Endereco.EstadoId = estado.EstadoId;

EDIT

According to comments, two properties are missing for the Entity Framework to work correctly:

Models \ Endereco.cs

public class Endereco
{
    ...
    public int EstadoID { get; set; }
    ...
}

Models \ Anuncio.cs

public class Anuncio
{
    ...
    public int EnderecoID { get; set; }
    ...
}
    
01.04.2014 / 19:52