1
<textarea id="TextAreaSend" runat="server" name="SendText">

I created text area to write something.And will save it to database with linq to entity.

if (!String.IsNullOrEmpty(TextAreaSend.InnerText))
        {

            int ticketno = Convert.ToInt32(ViewState["TicketNo"]);
            var source = from tickettext in entities.Tickets
                         where tickettext.TicketNo == ticketno
                         select tickettext;
            Ticket ticket = source.Single();
//This is where null point exception is
            ticket.Answer.AnswerText = TextAreaSend.InnerText;

            entities.SaveChanges();
        }

ticket.Answer.AnswerText = TextAreaSend.InnerText; In this line i receive;

Object reference not set to an instance of an object.Why is that? How can i fix it?

  • What is `ticket.Answer`? Are you sure that is not what is giving you the null reference? – Simon C Dec 15 '14 at 22:00
  • It is a class created by entity Ticket.It is a table in my database with navigation property i am just pointing where to write. – YourSolutionPartner Dec 15 '14 at 22:05
  • But i will check something – YourSolutionPartner Dec 15 '14 at 22:05
  • `ticket.Answer` is likely the item that's `null`. If it's not failing on the first line of that code when it does the null or empty check on `TextAreaSend.InnerText`, then it can't be failing when reading it for the assignment to `AnswerText`. – Cᴏʀʏ Dec 15 '14 at 22:09

2 Answers2

2

If it's not failing on the first line of that code when it does the null or empty check on TextAreaSend.InnerText, then it can't be failing for the same reason when reading the property value for the assignment to AnswerText.

ticket cannot be null here either because you would receive a different exception if 0 or more than 1 Ticket was returned by the query.

What we have left is that ticket.Answer is likely the item that's null here, not ticket or TextAreaSend. You are attempting to write to a property on an object that is null.

Cᴏʀʏ
  • 97,417
  • 19
  • 158
  • 183
  • I should have added ticketno into database.It just couldnt find the ticketno and answerText so cant find anything..Sorry my mistake i was a little rushed to do this – YourSolutionPartner Dec 15 '14 at 22:22
1

I would check into how many entities are being returned when you call "source.Single()". There can be exceptions thrown if there is more than one entity being returned or no entities being returned when using "Single()". Additionally, if you use "SingleOrDefault()", you can do a check for null prior to moving on with the rest of your code.

Joel Priddy
  • 441
  • 2
  • 12