InvalidOperation for HashSet field even with conversion defined

I have a db object defined with several HashSet<string> fields.

I defined conversions for those fields using the following:

        builder.Entity<DictionaryDBObject>(bldr =>
        {
            bldr.Property(dbobj => dbobj.Additions)
                .HasConversion<List<string>>(
                    wordSet => wordSet!.ToList<string>(),
                    wordList => wordList!.ToHashSet<string>()
                 );
        });

But I still get the following error:

System.InvalidOperationException: 'The type 'HashSet<string>' cannot be used as a primitive collection because it is not an array and does not implement 'IList<string>'. Collections of primitive types must be arrays or ordered lists.'

Does the Mongo EF provider support HasConversion? How can I go about troubleshooting this?

Thanks in advance,

  • Johnson

Hi Johnson.

While we do support HasConversion for primitive types we don’t (yet) support it for primitive collections. This looks like an oversight as we didn’t have an open ticket for it.

I’ve opened a ticket at https://jira.mongodb.org/browse/EF-205 which will go through triage and we’l then have some idea of when it can be addressed.

1 Like

Thanks for the update (and for letting me know i’m not just doing something stupidly wrong :grin:)

So I’ve dug in some more and things are a bit strange.

EF9 and CosmosDB throw the same error as our provider. In fact there is an open ticket for it on EF at Support `HasConversion` to primitive collection types · Issue #33688 · dotnet/efcore · GitHub

I thought originally it would work because my test on EF8 Comos worked just enough to load and save data without throwing but I suspect that was more luck than intent.

Collections in EF are a bit more involved that regular types given that EF needs to snapshot and compare them for the whole change-tracking etc. That happens up at CLR level not at the DB conversion level so it knows nothing about the types you’re trying to map from up there. Not to mention that even if it did support it you’d never be able to do things like .Where(d => d.Additions.Count > 0) as Count can never be translated as it’s a property on an “unknown” CLR type.

I don’t have any insight into the EF teams priorities but I suspect this is quite a large request with at-best a rough experience. It might be easier for them (or perhaps us) to just natively support HashSet.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.