user161433
user161433

Reputation: 4519

EntitySQL -- Object reference not set to an instance of an object

I am getting this error when I try to do an insert on a column that is a foreign key. Here is how I am assigning the value

var at = MvcApplication1.Entity.alttitles.Createalttitles(0, altTitleText);
        at.question.question_id = questionid;   //Error here
        at.userinfo.user_userid = _AuthorID;    //Error here
        context.AddToalttitles(at);
        res = context.SaveChanges();

When I made the question_id and the userid a foreign key I started getting this error. Is there a way to fix this?

Upvotes: 0

Views: 886

Answers (2)

marc_s
marc_s

Reputation: 755541

Most likely, the "question" is a referenced entity, right? Those are not included by default in your query - you'll need to specifically either include them in your first query

var at = MvcApplication1.Entity.alttitles
              .Createalttitles(0, altTitleText)
              .Include("question");

Is "question" a 1:1 or 1:n navigation property? In the 1:n case, you can check the "question" property directly:

if(!at.question.IsLoaded)
{
   at.question.Load();

   ....
}

In a 1:1 navigation property case, you probably have a "QuestionReference" property as well:

if(!at.QuestionReference.IsLoaded)
{
   at.QuestionReference.Load();

   ....
}

Marc

Upvotes: 1

Gregoire
Gregoire

Reputation: 24882

Check if at is not null before assigning its properties?

Upvotes: 0

Related Questions