0

Here is my code:

            int loanAppFundId = 0;
            var loanAppDb = db.LoanApplications.FirstOrDefault(s => s.LoanId == vm.LoanId);

            if (loanAppDb != null)
            {
                if (vm.FundID != null && loanAppDb.FundID !=0)
                {
                    if (loanAppDb.FundID != vm.FundID)
                    {
                        string oldFund = "", newFund = "";
                        loanAppFundId = loanAppDb.FundID;

                        var oFund = db.Funds.Where(s => s.FundID == loanAppFundId);
                    }
                }
            }

In the last line where I'm trying to retrieve fund based on the loanAppFundId is where the exception happens, if I set there 0 or some other variable it proceeds without any issue but whenever I try to set some variable I'm getting the error.

On purpose I initialized variable loanAppFundId with value 0, but again I'm getting error that the reference object is not set to an instance of an object.

If I set some dummy value in the db.Funds.Where query I'm able to get the loanAppDb.FundID value without any issue.

What am I doing wrong? I have multiple checks for the value if it's null or no.

Edit

I am not sure how this one is duplicate since I'm asking with real example, not a generic question.

halfer
  • 18,701
  • 13
  • 79
  • 158
Laziale
  • 7,259
  • 39
  • 131
  • 229
  • Only you can debug your own program and see where the exception is thrown and inspect the stack trace. Any "other set of eyes" can't help you with that. – Gert Arnold Sep 15 '17 at 09:20
  • The exception is thrown at the very first line of the code, which is int loanAppFundId = 0; – Laziale Sep 15 '17 at 09:22
  • That's impossible. Must be the line before that. – Gert Arnold Sep 15 '17 at 09:23
  • Nope, as I'm saying in my question explanation, if I set some specific value, lets say 22 insteead of loanAppFundId variable in the db.Funds.Where line the app runs without any issue. – Laziale Sep 15 '17 at 09:25
  • Could you include a stack trace (or a screenshot of the exception occurring)? – mjwills Sep 15 '17 at 10:44

1 Answers1

0

Obviously even if loanAppDb is not null but loanAppDb.FundID is null. To avoid it you can check loanAppDb.FundID for null too:

 if (vm.FundID != null && loanAppDb.FundID!= null && loanAppDb.FundID !=0)
 {
      //your magic
 }
Ashkan Mobayen Khiabani
  • 30,915
  • 26
  • 90
  • 147