0

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?

Tomasito
  • 1,864
  • 1
  • 20
  • 43

1 Answers1

1

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();
    }
}
Scott
  • 21,211
  • 8
  • 65
  • 72
  • Additionally in T-SQL you can: `IF EXISTS(SELECT TOP(1) 1 FROM [dbo].[ApplicationObject] AS a) BEGIN PRINT 'Exists' END`. You can use `EXISTS` in both ways. It is confusing, you have right. – Tomasito Mar 17 '14 at 14:27
  • @Tomasito I see what you are saying but thats still a subquery of `EXISTS` with the `IF EXISTS` being the outer query, but the point is moot anyway because the functionality doesn't exist and you will need to extend the dialect provider if you want it. Please remember to up vote if it's useful. Thanks – Scott Mar 17 '14 at 15:47