© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•8mo ago•
2 replies
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();
 }
   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
GitHub - neiomi1/StockExchange
Contribute to neiomi1/StockExchange development by creating an account on GitHub.
GitHub - neiomi1/StockExchange
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources
Was this page helpful?

Similar Threads

Recent Announcements

Similar Threads

The instance of entity type 'OptimizerInstanceEntity' cannot be tracked
C#CC# / help
2y ago
✅ EF Core 8: System.InvalidOperationException: 'The instance of entity type cannot be tracked..
C#CC# / help
10mo ago
✅ Urgent | Cannot update property in EF because another instance with the same key is being tracked
C#CC# / help
3y ago
❔ Generic entity type in EF Core
C#CC# / help
4y ago