0

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?

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

5 Comments

Your examples are backwards. "Reference" is for 1:1.
oops - thanks for pointing that out! Haven't been using it much lately (waiting for EF4), so my memory begins to slip :-)
Createalttitles is a entity sql create function to insert new rows in the database. It does not have an Include option in intelisense
ah okay, I didn't know if it was returning a IQueryable<T> interface or not; in that case, do any of the other ideas help? I am almost certain this is the root cause of the problem - the "question" property is not being populated automatically (since EF does not do that)
OK..No problem..I will try this as soon as I get home..thank you
0

Check if at is not null before assigning its properties?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.