OrmLite SqlExpression - how to tell if table is already joined?

Is there any way to tell if a table has already been joined in a SqlExpression<T>?

I need to automatically add join a table onto a base query for ordering purposes, but the table should only be joined if it wasn’t already joined in the base query.

Base query:

SELECT "Order"."Id", "Order"."SalesChannelId", "Order"."DateCreated"
FROM "Order"
WHERE "DateCreated" > '20150101'

Query with ordering:

SELECT "Order"."Id", "Order"."SalesChannelId", "Order"."DateCreated"
FROM "Order"
INNER JOIN "SalesChannel" ON "SalesChannel"."Id" = "Order"."SalesChannelId"
WHERE "DateCreated" > '20150101'
ORDER BY "SalesChannel"."Name"

I see there is the IsJoinedTable(Type type) method, but it’s private. It would be helpful if you make that method public.

Doesn’t seem like there is.

Are you building up the SqlExpression somewhere out of the Service method? Are you able to show how you’re currently generating the SqlExpression?

Do you need it to be a runtime type? Do you think exposing a IsJoinedTable<T>() instead would work for your use case?

Yes, I’m adding the order by expression in a shared extension method, so it has no way to know what tables are in the join expression.

My current solution is a horrible hack, but it works:

public static SqlExpression<T> OrderByWithDirection<T>(this SqlExpression<T> expression, string orderBy, bool replaceFkFieldWithDescription = false)
var isFkTableJoined = expression.FromExpression.Contains("JOIN " + dialectProvider.GetQuotedTableName(fkModelDef));

Exposing IsJoinedTable(Type type) should be all I need for this. I would be using a runtime type, so IsJoinedTable<T> won’t work.

It would be nice to know the join type (e.g. INNER, LEFT, etc), but that is not strictly necessary for my purposes.

The use case is simply to automatically add an order by expression from a string like "SalesChannelId DESC". But in this case, SalesChannelId is a FK to a the SalesChannel table, so I wan’t to allow that to be automatically replaced with "SalesChannel"."Name" DESC. This will be used for dynamically ordering data displayed in a grid view.

Cool, just made IsJoinedTable() public in this commit.

This change is now available from v4.0.47 that’s now available on MyGet.