Q:

Search if exist before insert in Linq DB in C# for WP8

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.

A:

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...

