0

I've got a problem, while trying to insert a new row into a SQL Server database with help of LINQ to SQL.

Here is the code:

[HttpPost]
public ActionResult QuestionsAnswers(UserQuestion userQuestion)
{
        if (ModelState.IsValid)
        {
            var newUserQuestion = new QuestionAnswer();

            newUserQuestion.Question = userQuestion.Question;
            newUserQuestion.From = userQuestion.From;

            ViewBag.QuestionSent = true;
            QuestionAnswerDb.QuestionAnswers.InsertOnSubmit(newUserQuestion);
            QuestionAnswerDb.SubmitChanges();
            return View(AnswersList);
        }

        ViewBag.QuestionSent = false;
        ViewBag.From = userQuestion.From;
        ViewBag.Question = userQuestion.Question;
        return View(AnswersList);
}

And I get an error while trying to "submit" a new UserQuestion (that has only From and Question in it), QuestionAnswer has columns: Id, From, Question, Answer (this one is nullable):

Cannot insert explicit value for identity column in table 'QuestionAnswer' when IDENTITY_INSERT is set to OFF.

I thought that Linq-to-SQL should handle Identity autoincrement columns by itself. Now I think, that I was wrong...

Any clues on how to properly set an Id for this object?

Thanks in advance.

4

2 回答 2

1

尝试将 id 显式设置为 null 。它可能被隐式设置为 0。

于 2013-07-02T18:47:02.420 回答
1

您需要设置一个字段(通常是 id 字段)以在数据库中具有标识。Linq 不会自动为您执行此操作。您可以通过以下方式做到这一点:

 Open your table in Sql Server Management Studio
 right click Design
 Open up Column Properties under the field you want to set as your identity(ID)
 Expand Identity Specification
 Set (Is Identity) to Yes.
于 2013-07-02T18:47:10.587 回答