C#C
C#6mo ago
GamerWoona

✅ EF: Instance of Entity Type cannot be tracked (already being tracked)

I am currently doing a little webapi project (https://github.com/neiomi1/StockExchange (it's messy right now, i know)) but am stumbling into the following error while running it for a while:
The instance of entity type 'Tag' cannot be tracked because another instance with the key value '{Id: 2}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.'

The SimulationService BackgroundService creates news daily at simulation speed but I must be creating the News wrong. The relevant classes should be SimulationService.cs, RandomCompanyNews.cs, News.cs, NewsTag.cs, Tag.cs

Excerpt from SimulationService.cs
   private async Task SimulationLoop(CancellationToken cancellationToken)
   {
       using (var scope = Services.CreateScope())
       {
          [...]
           await SetAppTime(scope);
           using var db = scope.ServiceProvider.GetRequiredService<StockExchangeDb>();
           await CreateNews(db);
          [...]       
        }
   }
 private async Task CreateNews(StockExchangeDb db)
 {
     var tags = await db.Tags.AsNoTracking().ToListAsync();
     var distinctTags = tags.Distinct();
     var news = RandomCompanyNews.GetRandomNews(tags);
     Debug.WriteLine($"Creating news {news.Title}");
     var newsTags = news.NewsTags;
     news.NewsTags = new List<Models.NewsTag>();
     await db.News.AddAsync(news);
     await db.SaveChangesAsync();
     news.NewsTags = newsTags;
     foreach (var tag in news.NewsTags)
     {
         tag.NewsId = news.Id;
     }
     await db.SaveChangesAsync();
 }
GitHub
Contribute to neiomi1/StockExchange development by creating an account on GitHub.
Was this page helpful?