[CSHARP-471] Support Casting in Linq Queries Created: 17/May/12  Updated: 02/Apr/15  Resolved: 22/May/12

Status: Closed
Project: C# Driver
Component/s: None
Affects Version/s: 1.4.2
Fix Version/s: 1.5

Type: New Feature Priority: Minor - P4
Reporter: Andy Clapham Assignee: Craig Wilson
Resolution: Done Votes: 0
Labels: linq,query
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Backwards Compatibility: 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.



 Comments   
Comment by Craig Wilson [ 22/May/12 ]

pulled into master

Generated at Wed Feb 07 21:36:56 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.