0

I have an if statement which checks whether or not an entry exists in my DB. The code correctly checks if an email address is already present, however if the email does not exist i get an error:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot perform runtime binding 
on a null reference at CallSite.Target(Closure , CallSite , Object ) at 
ASP._Page__footer_cshtml.Execute()

But if i remove the code that gets the existing email, these lines:

var getrecord = db.QuerySingle("Select Email from Registrations where email = @0", email); 
emailexists = getrecord.email;

the data is saved back to the DB with no problems. Not sure if its because i'm using the same Db helper?

  try
            {
                var db = Database.Open("MiniDB"); 
                var getrecord = db.QuerySingle("Select Email from Registrations where email = @0", email); 
                emailexists = getrecord.email;
                if (emailexists != ""){
                    msg = "This Email address is already registed";    
                    saved = false;
                }
                else {
                    var insertCommand = "INSERT INTO Registrations (Email, Name, regDate) VALUES(@0, @1, @2)"; 
                    db.Execute(insertCommand, email, name, regDate); 
                    saved = true;
                }
            }
            catch (Exception ex)
            {

                msg = ex.ToString();
                saved = false;
            }
davey
  • 1,544
  • 4
  • 26
  • 41

1 Answers1

0

One thing I ran into while retrieving (then testing) values within my database in WebMatrix was, depending on the field within the database, that after querying the database and storing the value in a variable, "", null, and System.DBNull.Value were three different things and checking for empty string or simply null was throwing errors for me in much the same way as your example.

Hopefully, I am helping with this (this may not be your issue, but I know it stumped me under similar circumstances, for quite a while, as I had never seen DBNull before).

This DBNull value traveled from the database to the variable I assigned the field value to, as it was a Session Variable and treated like an object. I'm not sure if this DBNull value would still be allowed to be stored in a regular variable (and not converted to regular null). Also, I believe I was using binary data (images) at the time, not sure if that would make a difference either but...

In the end, for my code, when checking to see a field (in the database) was empty, null, etc. I used something like this (only with a session variable instead of your regular variable):

if (emailexists != "" && emailexists != null && emailexists != System.DBNull.Value)
{
    //code goes here.
}

I hope this helps!

VoidKing
  • 6,282
  • 9
  • 49
  • 81