StronglyTypedId icon indicating copy to clipboard operation
StronglyTypedId copied to clipboard

How to use string functions like `Contains` or `StartWith` with string backed StronglyTypedId for Like queries in ef core

Open amit-srivastava-007 opened this issue 1 year ago • 3 comments

Hello, I'm having a situation where a StronglyTypedIdBackingType.String ids need to be used in a ef core query with StartsWith. Currently, I'm not seeing any string function available for such ids. Please guide me how to use it.

I'm using v1.0.0-beta06 of the package

Example:

let's say abc/efg/mnpxyz is a value of an Id field stored as hierarchy for city/ward/building for Office entity.

public class Office
{
  [StronglyTypedId(backingType: StronglyTypedIdBackingType.String)]
  public partial struct Id { }
}

I want to write query

Office.Where(x=>x.Id.StartsWith("abc").Select(x=>x);

amit-srivastava-007 avatar Jan 30 '24 18:01 amit-srivastava-007

Unfortunately, I think the short answer is that you can't currently. I'm not aware of a mechanism in EF Core to allow this currently. I'm certainly interested if someone can show how to make it work, but the IDs generally are intended to be opaque IDs.

andrewlock avatar Feb 12 '24 22:02 andrewlock

You could take a look at this: https://learn.microsoft.com/en-us/ef/core/querying/user-defined-function-mapping#mapping-a-method-to-a-custom-sql

I used it once to make an important business calculation available in EFCore queries, it was easier than I expected.

loop8ack avatar Jul 04 '24 01:07 loop8ack