craiggwilson / Simple.Data.MongoDB

MongoDB adapter for Simple.Data
35 stars 10 forks source link

Have to catch a Null Reference Exception when checking if a record exists #1

Closed booyaa closed 12 years ago

booyaa commented 13 years ago

I've got a webpage that flicks between prev and next days, during the Page_Load event I try to check if there's any data for the current date. Here's my code:

dynamic foodDiary;

try
{
    foodDiary = db.Diary.FindByDate(DiaryDate.ToShortDateString());
}
catch (NullReferenceException)
{
    foodDiary = null;
}

if (foodDiary != null)
   .. report no entries for today
else
   .. display food diary

Here's the stack trace from the exception:

StackTrace " at Simple.Data.MongoDB.BsonDocumentExtensions.ToDictionary(BsonDocument document)\r\n at Simple.Data.MongoDB.MongoAdapterFinder.FindOne(MongoCollection`1 collection, SimpleExpression criteria)\r\n at Simple.Data.MongoDB.MongoAdapter.FindOne(String tableName, SimpleExpression criteria)\r\n at Simple.Data.Database.FindOne(String tableName, SimpleExpression criteria)\r\n at Simple.Data.Commands.FindByCommand.Execute(DataStrategy dataStrategy, DynamicTable table, InvokeMemberBinder binder, Object[] args)\r\n at Simple.Data.DynamicTable.TryInvokeMember(InvokeMemberBinder binder, Object[] args, Object& result)\r\n at CallSite.Target(Closure , CallSite , Object , String )\r\n at HelloWebForms.Diary.Page_Load(Object sender, EventArgs e) in C:\Documents and Settings\Administrator\My Documents\Visual Studio 2010\Projects\HelloWebForms\HelloWebForms\Diary.aspx.cs:line 40" string

incidentally line 40 is this bit of code in the Try/Catch: foodDiary = db.Diary.FindByDate(DiaryDate.ToShortDateString());

I'd prefer just checking if the object is null, if it's possible.

Thanks!

craiggwilson commented 13 years ago

Thanks for reporting. Is there anyway you could write a test that would illustrate this issue? The method at the top of the stacktrace is called constantly (and as such, all the tests call this method and none of them are failing), so the scenario you are in is going to be hard for me to reporoduce.

booyaa commented 13 years ago

hiya, will upload test code on friday

booyaa commented 13 years ago

hiya, got test code written (zipped up solution file), is there a place on github I can upload to?

booyaa commented 13 years ago

Craig,

I think I'm being dim, didn't realise that the nullreference exceptions are caused when checking for any properties that don't exist w.r.t ExpandoObjects. I suspect this also applies when db.find returns no records.

I'm happy to close this issue if you are.

craiggwilson commented 13 years ago

IF you are comfortable that this is a you thing and not a me thing, then by all means, close it up.