Uploaded image for project: 'C# Driver'
  1. C# Driver
  2. CSHARP-538

OfType() followed by Count() in a LINQ query fails

    • Type: Icon: Bug Bug
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • 1.6
    • Affects Version/s: 1.5
    • Component/s: None
    • None

      To reproduce use these classes:

      public class B
      {
          public ObjectId Id;
      }
      
      public class C : B
      {
      }
      

      and this test code:

      var server = MongoServer.Create("mongodb://localhost/?safe=true");
      var database = server.GetDatabase("test");
      var collection = database.GetCollection<B>("test");
      
      collection.Drop();
      collection.Insert(new B());
      collection.Insert(new C());
      collection.Insert(new C());
      
      Console.WriteLine(collection.AsQueryable<B>().OfType<C>().Count()); // should write 2
      

      It throws this exception:

      System.InvalidCastException: Unable to cast object of type 'MongoDB.Driver.Linq.Projector`2[ConsoleApplication1.B,ConsoleApplication1.C]' to type 'MongoDB.Drive
      r.MongoCursor'.
         at MongoDB.Driver.Linq.SelectQuery.<TranslateCount>b__2(IEnumerable source) in C:\work\rstam\mongo-csharp-driver\Driver\Linq\Translators\SelectQuery.cs:line 416
         at MongoDB.Driver.Linq.SelectQuery.Execute() in C:\work\rstam\mongo-csharp-driver\Driver\Linq\Translators\SelectQuery.cs:line 210
         at MongoDB.Driver.Linq.MongoQueryProvider.Execute(Expression expression) in C:\work\rstam\mongo-csharp-driver\Driver\Linq\MongoQueryProvider.cs:line 155
         at MongoDB.Driver.Linq.MongoQueryProvider.Execute[TResult](Expression expression) in C:\work\rstam\mongo-csharp-driver\Driver\Linq\MongoQueryProvider.cs:line 131
         at System.Linq.Queryable.Count[TSource](IQueryable`1 source)
         at ConsoleApplication1.Program.Main(String[] _args) in C:\Users\Robert Stam\documents\visual studio 2010\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs:line 47
      

            Assignee:
            craig.wilson@mongodb.com Craig Wilson
            Reporter:
            robert@mongodb.com Robert Stam
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: