Using .NET Core 2.1, Entity Framework Core and NPGSQL.
I create a new record:
await _context.music.AddAsync(song);
await _context.SaveChangesAsync();
Then, within the same function, I do a few calculations (which I cannot do at the time of Creation) and then call Update (having updated the Comments field only):
_context.music.Update(song);
await _context.SaveChangesAsync();
Here is the class of "Song":
public class Song
{
[Key]
public int SongId { get; set; }
public int Title{ get; set; }
public string Comments{ get; set; }
//Navigation Properties
public virtual ICollection<Foo> Foos { get; set; }
}
In my MusicContext:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ForNpgsqlUseIdentityColumns();
modelBuilder.Entity<Foo>()
.HasOne(m => m.Song)
.WithMany(r => r.Foos)
.HasForeignKey(m => m.SongId);
}
This is the exception I get:
System.AggregateException: One or more errors occurred. (One or more errors occurred. (The instance of entity type 'Song' cannot be tracked because another instance with the same key value for {'SongId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.)) ---> System.AggregateException: One or more errors occurred.
Anyone have any ideas? :-/
Update? Btw, that line is redundant because afterAdd[Async]thesongis already tracked by the context, so all you need it to modify some properties and then callSaveChanges[Async]. Anyway, may be the key is what exactly are you doing between the two shown snippets. I guess minimal reproducible example is needed. - Ivan Stoev