CodexBloom - Programming Q&A Platform

How to implement guide with entity framework core not tracking related entities on savechanges in .net 6

πŸ‘€ Views: 1 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-03
entity-framework-core dotnet-6 csharp

I'm converting an old project and I need help solving I'm updating my dependencies and I'm working with a frustrating scenario with Entity Framework Core (EF Core) while trying to save changes to my database..... I have a `Product` entity that has a one-to-many relationship with a `Review` entity. When I try to add a new `Review` and save changes, the `Review` entity is not being tracked, and thus not saved to the database. Here's a simplified version of my entity classes: ```csharp public class Product { public int Id { get; set; } public string Name { get; set; } public ICollection<Review> Reviews { get; set; } = new List<Review>(); } public class Review { public int Id { get; set; } public string Comment { get; set; } public int ProductId { get; set; } public Product Product { get; set; } } ``` In my repository method, I’m trying to add a review like this: ```csharp public void AddReview(int productId, Review review) { using (var context = new MyDbContext()) { var product = context.Products.Include(p => p.Reviews).FirstOrDefault(p => p.Id == productId); if (product != null) { product.Reviews.Add(review); context.SaveChanges(); } } } ``` The strange part is that when I debug the application, I can see that the `Reviews` collection of the `product` object gets updated with the new review, but when I check the database after calling `SaveChanges()`, the review is missing. I’m not getting any exceptions, but the review isn’t inserted into the database. I’ve looked through the EF Core documentation and tried using the `ChangeTracker` to force tracking, but it didn't help. My EF Core version is 6.0.0. Any insights on why this might be happening or what I am doing wrong? Could it be related to the fact that I'm using a detached entity in this context? Is there a better approach? For context: I'm using Csharp on Ubuntu 22.04. I'm on Windows 11 using the latest version of Csharp.