Open Drago95 opened 2 days ago
Note for team: I investigated this and it is not really a regression. It is one of those quite common model diffing cases where each time the model is compared it is still different even after applying the migration. Often this is a bug, but in this case it is not a bug because the model data contains DateTime.Now
:
modelBuilder.Entity<DiaryEntry>().HasData(
new DiaryEntry
{
Id = 1,
Title = "Went Hiking",
Content = "Went hiking with Joe!",
Created = DateTime.Now
},
We should be aware that this type of issue will now show up as a pending model changes error.
@Drago95 When EF adds a new migration, it compares the data in the old model to that in the current model. If it has changed, then the data is updated in the database. However, in your case the data will change every time EF looks at it, since DateTime.Now
will return a different value each time it is run. The DateTime should instead be a value that will not change from run to run unless that is explicitly intended.
Thanks - understood.
I'm assuming there's not much we can do here (except in theory generate the model twice and compare the resulting seeding values, so that we can error if they're different - would we go to the trouble)?
Adding a note to the docs in https://github.com/dotnet/EntityFramework.Docs/pull/4878.
@roji I think this is by-design, but I added the label to check opinions from the team, and to raise awareness that we will now start seeing this kind of error for these kinds of issue.
Yeah... As a limitation it feels like it would be nice to alert the user that they're doing something wrong, but I'm not sure it's worth investing in HasData() at this point to add this error/warning.
We would only be able to detect this using an analyzer.
We can indeed do an analyzer specifically for DateTime.Now - that doesn't seem too hard, but I'm also not sure I'd want us to invest the effort in HasData() at this point. It would also obviously be specific (there are any number of other non-deterministic functions). I'll bring to design to see if we want to keep it.
Repro Steps: 1) Create initial migration via command line (dotnet ef migrations add "AddDiaryEntryTable" --project .\DiaryApp\DiaryApp.csproj --context ApplicationDbContext) 2) Apply migration to database (dotnet ef database update --project .\DiaryApp\DiaryApp.csproj) 3) Uncomment OnModelCreating in ApplicationDbContext 4) Create a new migration (dotnet ef migrations add "AddedSeedingDataDiaryEntry" --project .\DiaryApp\DiaryApp.csproj --context ApplicationDbContext) 5) Try to apply the migration to database - get error
Diary.zip
EF Core version: 9.0.0 Database provider: (e.g. Microsoft.EntityFrameworkCore.SqlServer) Target framework: (e.g. .NET 9.0) Operating system: Windows 11 23H2 (Build 22631.4460) IDE: JetBrains Rider 2024.2.7