1
votes

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? :-/

1
Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values. Then post the error - Tom Dee
What line is generating the exception? The one that calls Update? Btw, that line is redundant because after Add[Async] the song is already tracked by the context, so all you need it to modify some properties and then call SaveChanges[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

1 Answers

0
votes

I would reconsider your approach. If you're in the same method doing an add then an update, I would just do the add at the bottom including the comment value from your calculations.