I have a many-to-many relationship and my tables are correct about the relationship in the database. The problem is that my insert works perfectly when you do not use an existing entity in the database, but when I search the database and add it again it understands that I am not only "referencing" but adding a new entity. >
entity news:
[Table("Noticia")]
public class
{
[Key]
public Guid Id { get; set; }
[Required]
[MaxLength(50)]
public string Titulo { get; set; }
#region Relationships
public virtual ICollection<Tag> Tags { get; set; }
#endregion Relationships
}
Tag model:
[Table("Tag")]
public class Tag
{
[Key]
[Required]
[MinLength(3), MaxLength(30)]
public string Descricao { get; set; }
#region Relationships
[Required]
public virtual ICollection<Noticia> Noticias { get; set; }
#endregion Relationships
}
this relationship (ICollection
Controller:
[HttpPost, ValidateAntiForgeryToken]
public ActionResult Create(NoticiaViewModel vModel)
{
if (vModel != null && vModel.ArquivoImagem != null && vModel.ArquivoImagem.ContentLength > 0)
{
vModel.Id = Guid.NewGuid();
vModel.DataPostagem = DateTime.Now;
vModel.Tags = ObterTags(vModel.TagsEmLinha, vModel.Id);
vModel.UsuarioId = User.ToAvatarPrincipal().AvatarIdentity.Id;
vModel.Imagem = new Imagem
{
Id = Guid.NewGuid(),
CaminhoImagem = FileUploaderHelper.Upload(vModel.ArquivoImagem, User.ToAvatarPrincipal().AvatarIdentity.TipoUsuario,vModel.Id.ToString())
};
if (ModelState.IsValid)
{
///TODO: Quando a tag já foi utilizada, esta dando erro de primary key já existente na Tag.
if (_noticiaService.Gravar(ModelBuilderHelper.BuildNoticia(vModel)))
return RedirectToAction("List");
}
}
return View(vModel);
}
private List<Tag> ObterTags(string tagsEmLinha)
{
if (!string.IsNullOrEmpty(tagsEmLinha))
{
Tag tagFromDb = null;
var tags = new List<Tag>();
if (tagsEmLinha.Contains(","))
{
foreach (var tagDescricao in tagsEmLinha.Split(','))
{
tagFromDb = DefineTag(tags, tagDescricao);
}
}
else
{
tagFromDb = DefineTag(tags, tagsEmLinha);
}
return tags;
}
return null;
}
private Tag DefineTag(List<Tag> tags, string tagDescricao)
{
Tag tagFromDb = _tagService.ObterPor(tagDescricao);
if (tagFromDb != null)
tags.Add(tagFromDb);
else
{
tags.Add(new Tag
{
Descricao = tagDescricao
});
}
return tagFromDb;
}
Remembering that by adding a non-existent news item with a nonexistent tag, it inserts all the tags correctly (insert news, tag and tagNoticia). But if I insert news for a tag that already exists (make the many-to-many relationship), the error occurs:
Error:
An entity object can not be referenced by multiple instances of IEntityChangeTracker.