I have a Net Core 3.1 MVC project where a Playlist can be created and added to an existing Team. I run in to problems when I try to save the Playlist entity with _context.Add(playlist) and then _context.SaveChangesAsync() with the following error:
Cannot insert duplicate key row in object 'dbo.Teams' with unique index 'IX_Teams_TeamName'. The duplicate key value is (Team Name Four).
The statement has been terminated.
My code:
PlaylistDTO dto = new PlaylistDTO();
dto.Name = "new playlist with related team";
dto.Team = _context.Team.FirstOrDefault(t => t.Id == id) // id comes from viewmodel
Playlist storeToDb = _mapper.Map<Playlist>(dto)
_context.Playlists.Add(storeToDb);
await _context.SaveChangesAsync(); // throws error cannot insert duplicates.
My entities:
public class Playlist: AuditEntity
{
// id comes from AuditEntity
public string PlayListName { get; set; }
public string Description { get; set; }
public Team Team { get; set; }
}
public class Team: AuditEntity
{
// id comes from AuditEntity
public string TeamName {get; set; }
// other properties, including other related entities
public ICollection<Playlist> Playlists {get; set;}
}
My DbConfig file
public class TeamDbConfig : IEntityTypeConfiguration<Team>
{
public void Configure(EntityTypeBuilder<Team> builder)
{
builder.ToTable("Teams");
builder.HasIndex(t => t.TeamName)
.IsUnique();
// one2many rel for playlist. One team can have multiple playlists
builder.HasMany(t => t.Playlists)
.WithOne(pl => pl.Team)
.IsRequired(false)
.OnDelete(DeleteBehavior.Restrict);
}
}
In a similar post it was explained that with .Add() EF will treat any objects as new (and so it cannot add an entity with restricted columns twice). However, I don't know how to get this to work. Loading it untracked vs tracked, setting the Entry().EntityState to Modified or Unchanged doesn't seem to do anything.
This seems to be a pretty standard thing to do, yet I cannot get it done. So, I have a few questions:
- Given what I want (a user can add an existing team to a new playlist), do I have the correct relationships defined between Team and Playlist?
- What do I need to use as a statement instead (or in addition to) the Add() statement that I now have?
_mapper.Map<Playlist>(dto)? It seems that there a newTeamobject is created.