ServiceStack using Service.Db.Exists<Poco>(object) throws exception when used with OrmLite.SqlServer

StackOverflow https://stackoverflow.com/questions/22416595

Question

I'm expecting that Exists<>() function will check if data exists in database:

if (!Service.Db.Exists<Poco.ApplicationObject>(applicationObject))
{
    Service.Db.Insert(applicationObject);
} 

but I'm getting System.NotImplementedException when running this code.

In OrmLiteReadExtensions.cs:

private static bool HasChildren<T>(this IDbCommand dbCmd, object record, string sqlFilter, params object[] filterParams)
{
  string str = OrmLiteConfig.DialectProvider.ToExistStatement(typeof (T), record, sqlFilter, filterParams);
  dbCmd.CommandText = str;
  return dbCmd.ExecuteScalar() != null;
}

Is it implemented in ServiceStack.OrmLite.SqlServer?

Was it helpful?

Solution

No the ToExistStatement method has not been implemented in the OrmLite.SqlServer dialect, but that's probably because the T-SQL Exists method applies to subqueries and not for checking the existence of records, in the way you want, and it is to avoid confusion.

If you read the dialect provider you will not find the ToExistStatement method.

Effectively you are looking for a method that does this:

SELECT TOP 1 id FROM applicationObjects WHERE id = ?;

You could write a ToExists method that creates a SELECT TOP 1 SQL to gain this functionality. You would need to create a custom SqlServerOrmLiteDialect and tell your connection to use it.

public class MyCustomSqlServerOrmLiteDialectProvider : SqlServerOrmLiteDialectProvider
{
    public static new MyCustomSqlServerOrmLiteDialectProvider Instance = new MyCustomSqlServerOrmLiteDialectProvider();

    public override string ToExistStatement(Type fromTableType, object objWithProperties, string sqlFilter, params object[] filterParams)
    {
        // return "SELECT TOP 1 ..."
        throw new NotImplementedException();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top