[CSHARP-507] System.NullReferenceException on Empty String comparison Created: 20/Jun/12 Updated: 20/Mar/14 Resolved: 04/Jul/12 |
|
| Status: | Closed |
| Project: | C# Driver |
| Component/s: | None |
| Affects Version/s: | 1.5 |
| Fix Version/s: | 1.6 |
| Type: | Bug | Priority: | Major - P3 |
| Reporter: | Zaid Masud | Assignee: | Robert Stam |
| Resolution: | Done | Votes: | 0 |
| Labels: | linq, linq,query | ||
| Remaining Estimate: | Not Specified | ||
| Time Spent: | Not Specified | ||
| Original Estimate: | Not Specified | ||
| Description |
|
The following code gives us a NullReferenceException in FirstOrDefault() implementation: collection.AsQueryable().Where(d => d.StringField == String.Empty).Select(d => d.SomeField).FirstOrDefault() |
| Comments |
| Comment by Zaid Masud [ 04/Jul/12 ] |
|
Thanks... I would consider an additional unit test for SingleOrDefault() as well although your fix seems to apply for both. |
| Comment by Robert Stam [ 04/Jul/12 ] |
|
Zaid, thanks for the additional information. That really helped in reproducing this and in coming up with a fix. The exception is only thrown if FirstOrDefault is called after a projection that returns a struct (bool is a struct), which is why we hadn't seen this before. |
| Comment by auto [ 04/Jul/12 ] |
|
Author: {u'date': u'2012-07-03T14:44:59-07:00', u'name': u'Robert Stam', u'email': u'robert@10gen.com'}Message: |
| Comment by Zaid Masud [ 03/Jul/12 ] |
|
System.NullReferenceException was unhandled |
| Comment by Zaid Masud [ 03/Jul/12 ] |
|
using System; namespace MongoDriverBug public bool BoolField { get; set; } } static void Main() { MongoDatabase db = MongoServer.Create("mongodb://localhost/?safe=true").GetDatabase("test"); db.DropCollection("Document"); IQueryable<Document> documents = db.GetCollection<Document>("Document").AsQueryable(); Console.WriteLine(documents .Where(d => d.Id == ObjectId.GenerateNewId()) .Select(d => d.BoolField) .FirstOrDefault()); Console.ReadKey(); } } |
| Comment by Zaid Masud [ 03/Jul/12 ] |
|
This turned out to be a slightly different issue. The empty string was causing no matches. So to re-phrase, the exception is thrown when there is a Where().Select().FirstOrDefault when the where clause results in no matches returned. i.e. collection.AsQueryable().Where(d => d.Id == ObjectId.GenerateNewId()).Select(d => d.BoolField).FirstOrDefault(); In our specific case, the field being selected is a boolean type but I'm not sure whether that is relevant. |
| Comment by Craig Wilson [ 28/Jun/12 ] |
|
I cannot reproduce this. If you could provide a stack trace of the error and a sample program to reproduce it, that would be immensely helpful. My program is below: using System; namespace GeneralConsole public string Firstname { get; set; } public string Lastname { get; set; }} static void Main(string[] args) ; // Connect to Mongo ); ); var parentName = collection.AsQueryable() parentName = collection.AsQueryable() Console.ReadKey(); |