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

Support Casting in Linq Queries

    XMLWordPrintableJSON

Details

    • Icon: New Feature New Feature
    • Resolution: Done
    • Icon: Minor - P4 Minor - P4
    • 1.5
    • 1.4.2
    • None
    • Fully Compatible

    Description

      Casting is not currently supported by the linq driver.
      We would like the ability to query collections containing derrived types with different properties.

      For example

       
              public class Base
              {
                  public string A { get; set; }
              }
       
              public class T1 : Base
              {
                  public string B { get; set; }
              }
       
              public class T2 : Base
              {
                  public string C { get; set; }
              }
       
              [Test]
              public void CastTest()
              {
                  var server = MongoServer.Create("...");
                  var db = server.GetDatabase("test");
                  var collection = db.GetCollection<Base>("castTest");
       
                  var t1 = new T1 { A = "T1.A", B = "T1.B" };
                  var t2 = new T2 { A = "T2.A" };
                  collection.Insert(t1);
                  collection.Insert(t2);
       
                  var query = from t in collection.AsQueryable() where t is T1 && ((T1)t).B == "T1.B" select t;
                  var results = query.ToList();
                  Assert.That(results.Count, Is.EqualTo(1));
                  Assert.That(results[0], Is.InstanceOf(typeof(T1)));
                  Assert.That(results[0].A, Is.EqualTo("T1.A"));
              }

      This test currently throws an error

      System.NullReferenceException : Object reference not set to an instance of an object.
      at MongoDB.Driver.Linq.SelectQuery.GetSerializationInfoMember(IBsonSerializer serializer, MemberExpression memberExpression) in C:\work\10gen\mongodb\mongo-csharp-driver\Driver\Linq\Translators\SelectQuery.cs: line 1539

      as the Convert expression is not handled.

      Attachments

        Activity

          People

            craig.wilson@mongodb.com Craig Wilson
            andy clapham Andy Clapham
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: