Trying to establish a many to many relationship in my db context, I got the following error while seeding data:
The instance of entity type 'Folder' cannot be tracked because another instance with the key value '{Id: folder001 }' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<UserFolder>(userFolder =>
{
userFolder.HasKey(ud => new { ud.UserId, ud.FolderId });
userFolder.HasOne(uf => uf.Folder)
.WithMany(f => f.Users)
.HasForeignKey(uf => uf.FolderId)
.IsRequired();
userFolder.HasOne(uf => uf.User)
.WithMany(f => f.Folders)
.HasForeignKey(uf => uf.UserId)
.IsRequired();
});
}
_
public class Folder
{
public string Id { get; set; }
public string FolderName { get; set; }
public virtual ICollection<UserFolder> Users { get; set; }
}
_
public class User
{
public string Id { get; set; }
public string UserName { get; set; }
public virtual ICollection<UserFolder> Folders { get; set; }
}
_
public class UserFolder
{
public string UserId { get; set; }
public virtual User User { get; set; }
public string FolderId { get; set; }
public virtual Folder Folder { get; set; }
}
Searching this error results mostly to answers talking about the need to use Scoped instead of Singleton to register the service, but here I am configuring my service this way: services.AddDbContext<DataContext>, also some answers say that it is needed to add .AsNoTracking().
So how can I get rid of this error ?