I'm trying to use the new .WithSqlFilter()
extension method to add the "WITH (NOEXPAND)" hint to the select statement generated against my indexed view. However, the output SQL is putting the hint after the WHERE clause instead of the FROM clause. My Customer DTO also has [Alias("CustomerInfo")]
. Is this the intended behavior or is it generating the SQL incorrectly?
var customer = db.From<Customer>()
.Where(ci => ci.CustomerId == customerCode)
.WithSqlFilter(sql => IsSqlServer(db) ? sql + " WITH (NOEXPAND)" : sql);
return db.Single(customer);
Edit: I needed the IsSqlServer method because I also have unit tests and other code that uses Sqlite instead of SQL Server and needed to be able to ignore the hint based on the connection.
private bool IsSqlServer(IDbConnection db)
{
var dialect = db.GetDialectProvider();
return dialect is ServiceStack.OrmLite.SqlServer.SqlServerOrmLiteDialectProvider ||
dialect is ServiceStack.OrmLite.SqlServer.SqlServer2012OrmLiteDialectProvider ||
dialect is ServiceStack.OrmLite.SqlServer.SqlServer2014OrmLiteDialectProvider ||
dialect is ServiceStack.OrmLite.SqlServer.SqlServer2016OrmLiteDialectProvider;
}
Generated SQL:
SELECT TOP 1 "CustomerId", "FirstName", "MiddleInitial", "LastName", "Address", "City", "State", "ZipCode", "DateOfBirth", "HomePhoneNumber", "CellPhoneNumber", "EmailAddress", "EnrollmentDate", "IsEmployee", "ModifyDate", "LastModifiedByEmployee"
FROM "CustomerInfo"
WHERE ("CustomerId" = @0) WITH (NOEXPAND)
PARAMS: @0=123456
The WithSqlFilter
gets called with the complete SQL statement so if you're concatenating " WITH (NOEXPAND)" at the end of the SQL string that's where it appends to.
To extend the FROM clause you can either replace it like:
.WithSqlFilter(sql => IsSqlServer(db)
? sql.Replace("FROM \"CustomerInfo\"", "FROM \"CustomerInfo\" WITH (NOEXPAND)")
: sql);
Or you can just extend the FromExpression
, e.g:
var q = db.From<Customer>()
.Where(ci => ci.CustomerId == customerCode);
q.FromExpression += " WITH (NOEXPAND)";