Robba
Robba

Reputation: 8324

How to query the actual value in Entity Framework core when using a Value Converter?

We have a fairly simple situation where an EF Core entity contains a value object that we map to a string:

builder.Property(_ => _.Nummer)
    .HasConversion(i => i.ToString(), i => ZijdeNummer.FromString(i))
    .IsRequired().HasMaxLength(9);

This works fine for retrieval and storage, but for filtering we're looking for a way to filter rows by substring. If it'd be a normal string column you can simply do something like this:

dbSet.TheTable.Where(t => t.Nummer.Contains("some text")).ToList()

Obviously the custom ZijdeNummer doesn't contain a recognized .Contains() method. I've tried using .ToString().Contains() but alas, this also doesn't work.

Finally, I've also tried accessing the column as if it were a shadow-property:

dbSet.TheTable.Where(t => EF.Property<string>(t, "Nummer").Contains("some text"))

But it won't be fooled as it still knows that EF.Property<T>(t, "Nummer") is not actually a string :(

Is there a way to make EF-Core just query the raw column type?

Upvotes: 7

Views: 2008

Answers (1)

Robba
Robba

Reputation: 8324

It turns out this is much easier than you'd expect. Simply cast the type to string (if no conversion exists, then first cast to object) and perform the comparison:

dbSet.TheTable.Where(t => ((string)(object)t.Nummer).Contains("some text")).ToList()

Upvotes: 16

Related Questions