0

I'm getting a null reference expception and can't figure out why this is happening. It's only happening when I add the LoanTeamMemberNameFunder property. I have about 50 other properties and this isn't happening. I'm checking if the string is null or empty before setting the property, then assigning to null if so, but am still getting the exception. What else can I do to try and resolve this issue?

[MaxLength(128)]
  public string LoanTeamMemberNameFunder { get; set; }




  MyContext db = new MyContext();

        int i = 0;

        try
        {
            foreach (LoanReportData data in cur)
            {
                Loan loan = new Loan();
                loan.Id = (data["Guid"] == String.Empty ? null : data["Guid"].ToString());
                loan.LoanTeamMemberNameFunder = String.IsNullOrEmpty(data["fields.LoanTeamMember.Name.Funder"].ToString()) ? null : data["fields.LoanTeamMember.Name.Funder"].ToString();



                db.Set<Loan>().AddOrUpdate(loan);

                if ((i % 100 == 0))
                {

                    db.SaveChanges();

                    Console.WriteLine("Total of " + i + " loans updated");
                }

                i++;
            }
        }
        catch (Exception ex)
        {
            db.SaveChanges();
            Console.WriteLine(ex);
        }



        db.SaveChanges();
        db.Dispose();

    }
}

}

dc922
  • 629
  • 3
  • 14
  • 27
  • 1
    Your null checking is off. You're calling `.ToString()` on a reference which may be null. Generally speaking, `.ToString()` will never return null, so checking whether it's null is useless. You should instead be checking whether `data["fields.LoanTeamMember.Name.Funder"]`, etc., is null. – Kirk Woll Feb 13 '16 at 17:24
  • Fixed it using this check for null: loan.LoanTeamMemberNameFunder = (data["fields.LoanTeamMember.Name.Funder"] == null ? null : data["fields.LoanTeamMember.Name.Funder"].ToString()); – dc922 Feb 13 '16 at 17:36
  • 1
    if you're on VS2015 / C# 6.0, you could simplify your code to `LoanTeamMemberNameFunder = data["fields.LoanTeamMember.Name.Funder"]?.ToString()` – Kirk Woll Feb 13 '16 at 17:38

0 Answers0