简体   繁体   中英

How to Fix This “system.nullreferenceexception object reference not set to an instance of an object” in mvc web service

In My Controller

public string Post(Order od)
        {

            string result = "";

            Database newDB= new Database("New");
            try
            {

              newDB.Execute(@"insert into TABLE_A(BranchID,CustomerName,BirthDate,BirthPlace) 
                Select @0,@1,@2,@3",
                new object[] {od.BranchID,od.CustomerName,od.BirthDate,od.BirthPlace});


                newDB.CloseSharedConnection();
                result = "succes";
            }
            catch (Exception Ex)
            {
                result = Ex.Message;

            }

            return result;
        }

in error message

System.NullReferenceException: Object reference not set to an instance of an object"

I try created a new object odr:

public string Post(Order od)
        {

            string result = "";
            Order odr = new Order();
            Database newDB= new Database("New");
            try
            {

              Log.Info("REQ:" + od.BranchID + "|" + od.CustomerName + "|" + od.BirthDate + "|" + od.BirthPlace);
              newDB.Execute(@"insert into TABLE_A(BranchID,CustomerName,BirthDate,BirthPlace) 
                Select @0,@1,@2,@3",
                new object[] {odr.BranchID,odr.CustomerName,odr.BirthDate,odr.BirthPlace});


                newDB.CloseSharedConnection();
                result = "succes";
            }
            catch (Exception Ex)
            {
                result = Ex.Message;
                Log.Error(Ex)             
            }

            return result;
        }

but the data that I've post is null. Please help my problem :(

NullRefException is one of the basic programming error you should learn and avoid. How did you set collectionDB? Or if it's not collectionDB was null, just share exception stacktrace here so we will see and help you point out the cause of this.

Besides, never catch the top-level Exception like this. Catching exception without logging is a bad practice in all cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM