CodexBloom - Programming Q&A Platform

Using C# 9 Record Types with Entity Framework Core 5 - implementing Change Tracking

👀 Views: 2 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-10
c# entity-framework-core records C#

I'm getting frustrated with I'm working on a personal project and I'm experiencing issues with change tracking when using C# 9 record types with Entity Framework Core 5....... I defined a simple record type for my entity, but when I attempt to update an existing entity in the database, it seems that EF Core is not detecting the changes properly. The application doesn't throw any exceptions, but the changes are not persisted to the database. Here's a simplified version of my record definition: ```csharp public record Product(int Id, string Name, decimal Price); ``` And I'm using the following code to update it: ```csharp public void UpdateProduct(Product updatedProduct) { using var context = new MyDbContext(); var existingProduct = context.Products.Find(updatedProduct.Id); if (existingProduct != null) { context.Entry(existingProduct).CurrentValues.SetValues(updatedProduct); context.SaveChanges(); } } ``` The scenario arises when I try to change the `Price` of an existing `Product`. After executing `UpdateProduct`, I check the database, and the `Price` remains unchanged. I've tried using `.Attach()` method as well, which didn't help either. I suspect this might be related to how EF Core handles records and their immutability. Any suggestions on how to effectively update records in EF Core or if there are best practices around using records with Entity Framework? I am using .NET 5 and EF Core 5.0.11. Thanks in advance! Thanks in advance! For context: I'm using C# on Windows. Am I missing something obvious? For reference, this is a production REST API. I'm developing on macOS with C#. Any examples would be super helpful. Is there a better approach?