Search code examples
starcounter

Starcounter query that returns base class only


Lets assume we have the non abstract base class A, which has a specialized class B. I now want to make a query that only returns instances of A, not B. Can this be achieved?


Solution

  • EDIT2

    Starcounter implements operator IS, which allows to check if an object belongs to the given type. However, the check include children and thus does not help. Implementation of operator IS NOT is missing, which I found after I tested it in the latest version of Starcounter. There is a ticket in Starcounter's issue tracker about this.

    So the answer to the question is: It is not possible to select objects of a base class without selecting objects of children classes using SQL in current version of Starcounter. The filter has to be implemented in C# during iteration over the query result. An example of application, which filters out objects of B:

    using System;
    using Starcounter;
    
    class Program {
        static void Main() {
            Db.Transact(delegate {
                new A { name = "a1" };
                new B { name = "b1" };
            });
            foreach (A a in Db.SQL<A>("SELECT a FROM A a"))
                if (!(a is B))
                    Console.WriteLine(a.name);
        }
    }
    
    [Database]
    public class A {
        public String name;
    }
    
    public class B : A {
    }
    

    The result of the program execution the first time will be:

    a1