This is my current EF Core model:
public class Application
{
[Key]
public string Name { get; set; }
public HashSet<string> Fields { get; set; }
}
The hashset property doesn't work on its own, so I've added this in OnModelCreating
:
modelBuilder.Entity<Application>()
.Property(e => e.Fields)
.HasConversion(
v => v.ToArray(),
v => new HashSet<string>(v));
That works in some cases, but there is a big issue with it.
When I insert an application initially, the hashset gets converted to a string array correctly, and the postgresql db driver stores it correctly.
However when I later get the application again, modify the hashset, and then call .SaveChanges();
it does not work!
I have to explicitly call ctx.Update(app);
for the changes to get saved.
I think that is because the HashSet<string>
instance does not change, only its content changes, so the change tracker won't be able to see any changes (but maybe I'm wrong about that reasoning).
How can I fix this?
The example here only has one HashSet, but other models will have many more properties that will all suffer from the same problem.
- Is there any way to make the change tracker aware of those changes?
- Is there maybe a way to implement a custom collection of some sort that will notify its "container" that it has been modified?
- Is it maybe possible to tell EF to check the value after the conversion, instead of the hashset itself?