0

I am working on a WP8 questions application, the application send the data to the DB but will skip the exist data. I have a class called "DBHelper.cs" and it contains

public static void InsertQuestion(Question oQuestion)
{
    using (var context = new QuestionContext(ConnectionString))
    {
        if(context.DatabaseExists())
        {
            Question oQuestionWord = (from ostd in context.Questions where ostd.Word == oQuestion.Word select ostd).Single();
            if (oQuestionWord.Word == null)
            {
                context.Questions.InsertOnSubmit(oQuestion);
                context.SubmitChanges();
            }
        }
    }
}

And this code in the mainpage.xaml.cs

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    Question oQuestion = new Question();
    oQuestion.Word = "One";
    DBHelper.InsertQuestion(oQuestion);``
    oQuestion = new Question();
    oQuestion.Word = "Two";
    DBHelper.InsertQuestion(oQuestion);
    oQuestion = new Question();
    oQuestion.Word = "One";
    DBHelper.InsertQuestion(oQuestion);
    base.OnNavigatedTo(e);
}

There is no errors when Building the solution, but it crashes when launching the app.

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
Afterlife
  • 79
  • 1
  • 10

1 Answers1

3

I believe the reason of the error is the Single method. Single throws an exception if it finds more than one record. Try using FirstOrDefault instead:

var oQuestionWord = context.Questions.FirstOrDefault(q => q.Word == oQuestion.Word);
if (oQuestionWord != null && oQuestionWord.Word == null)
{
    context.Questions.InsertOnSubmit(oQuestion);
    context.SubmitChanges();
}

And probably you didn't get a useful exception message because it happened in OnNavigatedTo event.You might want to take a look at this question...

Community
  • 1
  • 1
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • This code works perfect, just edit "(oQuestionWord != null && oQuestionWord.Word == null)" to "(oQuestionWord == null)",thank you! :D – Afterlife Jul 30 '14 at 17:43